使用httpClient访问https远程服务器调用远程接口并且传递参数以及忽略SSL证书的问题

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。使用httpClient访问https远程服务器调用远程接口并且传递参数以及忽略SSL证书的问题,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

使用httpClient访问https远程服务器调用远程接口并且传递参数以及忽略SSL证书的问题

首先写一个httpClient主要调用远程API和参数传递

import com.hxsj.inspection.common.util.SSLClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @program: inspection-project
 * @description: 使用httpClient访问远程api
 * @author: Chai.duolai
 * @create: 2019-04-15 16:19
 **/
@RequestMapping("httpClient")
@RestController
public class HttpClients {
    @PostMapping("/postNoArguments")
    public  String postNoArguments() throws Exception {
   //以下是我自己调用的接口需要传递的参数
        Random random=new Random();
        String accesskey="xxx";
        //获得一个随机数
        String nonce = String.valueOf(random.nextInt());
        //获得一个时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        StringBuffer stringBuffer=new StringBuffer();
        String secretkey="xxx";
        //将上面的三个参数按照顺序合并成一个字符串
        String signaturee = stringBuffer.append(secretkey).append(nonce).append(timestamp).toString();
        //在这里我要调用的api传递的第四个参数需要计算它的SHA1值(40位的)
        String signature= sha1(signaturee);
        //这里就是你要访问的具体地址了,填你自己的
        String url = "https://IP地址/api/token";
        //创建 MultipartEntityBuilder,以此来构建我们的参数
        MultipartEntityBuilder EntityBuilder = MultipartEntityBuilder.create();
//设置字符编码,防止乱码
        ContentType contentType= ContentType.create("text/plain", Charset.forName("UTF-8"));
//填充我们的文本内容,这里相当于input 框中的 name 与value
        EntityBuilder.addPart("accesskey", new StringBody(accesskey,contentType));
        EntityBuilder.addPart("nonce", new StringBody(nonce,contentType));
        EntityBuilder.addPart("timestamp", new StringBody(timestamp,contentType));
        EntityBuilder.addPart("signature", new StringBody(signature,contentType));

        CloseableHttpClient httpClient =null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //在这里必须强调一点的是,看你调用的接口需要的参数格式是什么
            //我这里接口的参数格式是form-data类型的,如果你需要传值json或者别的类型我在下面会写到,别急
//            httpPost.addHeader("Content-Type", "application/json");
            /*StringEntity se = new UrlEncodedFormEntity(formList, "utf-8");
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));*/
            httpPost.setEntity(EntityBuilder.build());
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,"UTF-8");
                    System.out.println("响应内容为"+result);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally {
        //在这里强调一下httpClient一定要关闭。不然会出错
            httpClient.close();
        }
        return result;
    }

在代码中我有说到我的第四个参数需要计算SHA1的值,下面代码可以参考

 public static String sha1(String data) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        md.update(data.getBytes());
        StringBuffer buf = new StringBuffer();
        byte[] bits = md.digest();
        for(int i=0;i<bits.length;i++){
            int a = bits[i];
            if(a<0) a+=256;
            if(a<16) buf.append("0");
            buf.append(Integer.toHexString(a));
        }
        return buf.toString();
    }

标题:由于本人也是第一次,所以尝试了很多坑,希望看到这篇博客的人可以帮到你

刚在在代码中说到了调用api传不同格式的参数问题,我看了一篇博客写的很好,你们可以根据它的改一下就好,我的参数是form-data方式格式的,当然了还有json类型的

插入链接:http://www.cnblogs.com/iscys/p/9595358.html 可以看看他的传递参数

接下来就是处理SSL证书的问题,第一次遇到,当时请教了很多人,这个我也是看了一篇博客的,如有侵权,望告知删除

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * @program: inspection-project
 * @description: 忽略安全证书
 * @author: Chai.duolai
 * @create: 2019-04-16 09:56
 **/
public class SSLClient extends DefaultHttpClient {
    public SSLClient() throws Exception{
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}
  • 本人的邮箱cduolai@163.com 如果有什么问题或者学术交流,很愿意和你一起探讨,可以把微信给你发送过去
    在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/159037.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!