httpclient的https请求

httpclient请求https接口解决方案

将https域名的安全证书导入到JDK的安全证书存储文件中

  1. 导出https域名安全证书(公钥)
    浏览器访问https的网站,一般使用IE浏览器打开,点击浏览器输入栏右边的锁(安全报告)-查看证书-详细信息-复制到文件,选择DER编码二进制 X.509(.CER)(D)
  2. 使用JDK提供的keytool命令将上面生成的.cer文件导入JDK/JRE/lib/security/cacerts中
    Windows 环境

    1
    keytool -import -file D:\cer\xxx.cer -keystore D:\Programs\Java\Java\jdk1.7.0_45\jre\lib\security\cacerts -trustcacerts

    输入口令:changeit即可。

信任所有

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}

public static String getHttps(String reqURL, Map<String, Object> params) {
CloseableHttpClient httpclient = createSSLClientDefault();
String queryString = "";
if (!StringUtils.contains(reqURL, "?")) {
queryString += "?";
}
for (Entry<String, Object> entry : params.entrySet()) {
queryString += ("&" + entry.getKey()) + "="
+ (String.valueOf(entry.getValue()));
}
queryString = queryString.replace("?&", "?");
HttpGet httpget = new HttpGet(reqURL+queryString);

String result = null;
try {
CloseableHttpResponse response = httpclient.execute(httpget);
System.out.println("response.getStatusLine(): "+response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
logger.info("Https request getByJson result: " + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
httpget.releaseConnection();
}
return result;
}

邵志鹏 wechat
扫一扫上面的二维码关注我的公众号
0%