httpClient请求https接口实现

本文介绍了如何在Java Spring Boot项目中,利用httpClient库来实现对HTTPS接口的请求。通过在pom.xml文件引入相关依赖,并重写HTTPClient方法,详细阐述了配置和调用过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近项目中和外部接口交互时遇到问题,项目本身是http形式的接口协议,需要请求https的接口协议,代码中使用的是httpClient进行实现,

1、pom文件引入:

 <dependency>
                   <groupId>org.apache.httpcomponents</groupId>
                   <artifactId>httpclient</artifactId>
                   <version>4.5.2</version>
               </dependency>

2、重写HTTPClient方法,代码块用到如下参数:

@Value("${keyStoreSim.path}")
String keyStorePath;

@Value("${trustStoreSim.path}")
String trustStorePath;

@Value("${keyStorePwd.Sim}")
String keyStorePwd;

@Value("${trustStorePwd.Sim:}")
String trustStorePwd;
 public String httpClientPost(String httpUrl, String inJson) throws Exception{
//        RequestConfig requestConfig = RequestConfig.custom()
//                .setConnectTimeout(5000).setConnectionRequestTimeout(1000)
//                .setSocketTimeout(5000).build();
        // 创建post请求
       /* HttpPost httpPost = new HttpPost(httpUrl);
        HttpResponse response = null;

        HttpEntity entity = null;
        StringEntity stringEntity = new StringEntity(inJson, ContentType.create("application/x-www-form-urlencoded", "UTF-8"));
        httpPost.setEntity(stringEntity);
        String responseContent = null;*/
//        try {

            // 创建默认的httpClient实例.
           // mailSimHttpClient = HttpClients.createDefault();
           // httpPost.setConfig(requestConfig);

            // 执行请求
         /*   response = getSimHttpClient().execute(httpPost);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");*/
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                // 关闭连接,释放资源
//                if (response != null) {
//                    response.close();
//                }
//                if (httpClient != null) {
//                    httpClient.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }

        HttpPost httpPost = new HttpPost(httpUrl);
//
        StringEntity entiy = new StringEntity(inJson, ContentType.create("application/x-www-form-urlencoded", "UTF-8"));
        httpPost.setEntity(entiy);
        Long time = System.currentTimeMillis();
        HttpResponse response = getSimHttpClient().execute(httpPost);
        Log.outSysLog("执行httpclient所需要的时间.getSimHttpClient.execute(httpPost)" + (System.currentTimeMillis() - time) );
        String responseContent ="";
        // 判断响应状态
        if (response.getStatusLine().getStatusCode() >= 300)
        {
            String str = "code:"+ MessageCode.INTERFACE_ID_WRONG.code+"HTTP Request is not success, Response code is "+ response.getStatusLine().getStatusCode()+",responseContent="+EntityUtils.toString(response.getEntity(), "UTF-8");
            throw new CommonsException(MessageCode.INTERFACE_ID_WRONG,str);
        }

        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode())
        {
            responseContent = EntityUtils.toString(response.getEntity(),"UTF-8");
            EntityUtils.consume(response.getEntity());
        }
        String rsp=responseContent.toString();
        return responseContent;
    }

 

/**
     * 注意:
     * 这里返回的Executor是单例的,并且可以直接注入到其他类中去使用
     * @return
     */
    @SuppressWarnings("deprecation")
    public HttpClient getSimHttpClient() throws Exception {
        Long time = System.currentTimeMillis();
          HttpClient client = new DefaultHttpClient();
        //CloseableHttpClient client = HttpClients.createDefault();
        SSLContext ctx = SSLContext.getInstance("TLS");
        System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
        KeyStore ks = KeyStore.getInstance("pkcs12");
        ks.load(new FileInputStream(keyStorePath), keyStorePwd.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("sunx509");
        kmf.init(ks, keyStorePwd.toCharArray());
        KeyStore ts = KeyStore.getInstance("jks");
        ts.load(new FileInputStream(trustStorePath), trustStorePwd.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509");
        tmf.init(ts);
        ctx.init(kmf.getKeyManagers(), new TrustManager[] { tm }, null);
        org.apache.http.conn.ssl.SSLSocketFactory ssf = new org.apache.http.conn.ssl.SSLSocketFactory(ctx);
        //SSLConnectionSocketFactory sslsf =
        //         new SSLConnectionSocketFactory(sslcontext, null, null,
        //                 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        ClientConnectionManager ccm = client.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        client = new DefaultHttpClient(ccm, client.getParams());
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                soketTimeOut);
        Log.outSysLog("封装httpclient所需要的时间.getSimHttpClient" + (System.currentTimeMillis() - time) );
        return client;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值