HTTP-GET带header请求
HTTP-POST带header请求
HTTPS-POST带header请求
Java
运行代码
复制代码
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//设置链接超时和请求超时等参数,否则会长期停止或者崩溃
public static String sendHttpsPost(String url, JSONObject params) {
String responseContent = null;
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try {
HttpPost httpPost = new HttpPost(url);
// header
httpPost.addHeader("AppKey", SystemConstants.APP_KEY);
httpPost.addHeader("Secret", SystemConstants.SECRET);
// body
httpPost.setEntity(new StringEntity(params.toString(), "UTF-8"));
httpClient = HttpClients.custom().setSSLSocketFactory(createSslConnSocketFactory()).setDefaultRequestConfig(requestConfig).build();
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
responseContent = EntityUtils.toString(httpEntity, "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(null != httpResponse) {
httpResponse.close();
}
if (null != httpClient) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* 创建SSL安全连接
* @return SSLConnectionSocketFactory
*/
private static SSLConnectionSocketFactory createSslConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
@Override
public void verify(String host, SSLSocket ssl) {
}
@Override
public void verify(String host, X509Certificate cert) {
}
@Override
public void verify(String host, String[] cns, String[] subjectAlts) {
}
});
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return sslsf;
}