HttpsClient.java
6.87 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package com.cjs.cms.util.net;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.web.util.UriTemplate;
public class HttpsClient {
private static final String HTTPS_URL = "https://192.168.10.186/pub/login";
private static final String KEY_STORE_TRUST_PASSWORD = "123456";
private static final String CLIENT_KEY_PASS = "123456";
private static CloseableHttpClient httpClient = null;
private static RequestConfig requestConfig = null;
private static final int TIME_OUT = 5000;
public static final Charset CHARSET = Charset.forName("UTF-8"); // httpclient读取内容时使用的字符集
public static void main(String[] args) throws Exception {
System.out.println(doGet(HTTPS_URL, new HashMap<String, String>()));
}
static {
try {
String path = HttpsClient.class.getResource("/ssl2/").getFile();
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream(new File(path + "/client.p12")),
KEY_STORE_TRUST_PASSWORD.toCharArray());
SSLContext sslcontext = SSLContexts.custom()
//忽略掉对服务器端证书的校验
.loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
})
//加载服务端提供的truststore(如果服务器提供truststore的话就不用忽略对服务器端证书的校验了)
//.loadTrustMaterial(new File("D:\\truststore.jks"), "123456".toCharArray(),
// new TrustSelfSignedStrategy())
.loadKeyMaterial(keyStore, CLIENT_KEY_PASS.toCharArray()).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory)
.build();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* POST请求
* @param uri 请求的URI
* @param params 请求参数
* @return 远程服务器相应,如果状态不是200,则返回null
*/
public static String doPost(String uri, Map<String, String> params) throws Exception {
HttpPost httpPost = new HttpPost(uri);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
//绑定到请求 Entry
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
formParams.add(new BasicNameValuePair(key, params.get(key)));
}
httpPost.setEntity(new UrlEncodedFormEntity(formParams, CHARSET));
response = httpClient.execute(httpPost);
if (response == null || response.getStatusLine().getStatusCode() != 200) {
return null;
}
HttpEntity entity = response.getEntity();
//使用EntityUtils的toString方法,传递编码,默认编码是ISO-8859-1
return EntityUtils.toString(entity, getContentCharSet(entity));
} catch (Exception e) {
throw e;
} finally {
if (response != null) {
response.close();
}
httpPost.releaseConnection();
}
}
/**获取响应的编码类型,默认为UTF-8*/
private static String getContentCharSet(final HttpEntity entity) throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String charset = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
}
}
if (StringUtils.isEmpty(charset)) {
charset = "UTF-8";
}
return charset;
}
/**
* Get请求
* @param uri 请求的URI
* @param params URL格式如下:http://xxx?a={a}&b={b}
* @return 远程服务器相应,如果状态不是200,则返回null
*/
public static String doGet(String uri, Map<String, String> params) throws Exception {
HttpGet httpGet = null;
CloseableHttpResponse response = null;
try {
if (params != null) {
uri = new UriTemplate(uri).expand(params).toString();
}
httpGet = new HttpGet(uri);
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
System.out.println(response);
if (response == null || response.getStatusLine().getStatusCode() != 200) {
return null;
}
HttpEntity entity = response.getEntity();
//使用EntityUtils的toString方法,传递编码,默认编码是ISO-8859-1
return EntityUtils.toString(entity, getContentCharSet(entity));
} catch (Exception e) {
throw e;
} finally {
if (response != null) {
response.close();
}
if (httpGet != null) {
httpGet.releaseConnection();
}
}
}
}