HttpClientUtils.java
8.55 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package com.bsth.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
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;
/**
* Created by panzhao on 2017/8/2.
*/
public class HttpClientUtils {
static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
private static ObjectMapper mapper = new ObjectMapper();
private final static String HTTPS = "https://";
private static SSLConnectionSocketFactory sslConnectionSocketFactory;
static {
try {
SSLContext sslCtx = SSLContext.getInstance("TLSv1.2");
sslCtx.init(null, new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}, null);
sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslCtx, new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
// TODO Auto-generated method stub
return true;
}
});
} catch (Exception e) {
logger.error("SSL context set fail: {}", e);
}
}
public static CloseableHttpClient defaultHttpClient(String url) {
if (url.startsWith(HTTPS)) {
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}
return HttpClients.createDefault();
}
public static StringBuilder get(String url) throws Exception {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
StringBuilder stringBuffer = null;
try {
httpClient = defaultHttpClient(url);
HttpGet get = new HttpGet(url);
//超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10500).setConnectionRequestTimeout(7000)
.setSocketTimeout(10500).build();
get.setConfig(requestConfig);
get.addHeader("Content-Encoding", "gzip");
response = httpClient.execute(get);
stringBuffer = getResult(response.getEntity());
} catch (Exception e) {
logger.error("", e);
} finally {
if (null != httpClient)
httpClient.close();
if (null != response)
response.close();
}
return stringBuffer;
}
/**
* raw post data
* @param url
* @param data
* @return
*/
public static StringBuilder post(String url, String data) throws Exception {
return post(url, data, new HashMap<>());
}
public static StringBuilder post(String url, String data, Map<String, Object> headers) throws Exception {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
StringBuilder stringBuffer = null;
try {
httpClient = defaultHttpClient(url);
HttpPost post = new HttpPost(url);
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/json;charset=UTF-8");
if (headers.size() > 0) {
for (Map.Entry<String, Object> header : headers.entrySet()) {
post.setHeader(header.getKey(), String.valueOf(header.getValue()));
}
}
//超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(2500).setConnectionRequestTimeout(2000)
.setSocketTimeout(3500).build();
post.setConfig(requestConfig);
if (data != null) {
post.setEntity((new StringEntity(data, "UTF-8")));
}
response = httpClient.execute(post);
stringBuffer = getResult(response.getEntity());
} catch (Exception e) {
logger.error("", e);
} finally {
if (null != httpClient)
httpClient.close();
if (null != response)
response.close();
}
return stringBuffer;
}
public static StringBuilder post(String url, HttpEntity entity) throws Exception {
return post(url, entity, new HashMap<>());
}
public static StringBuilder post(String url, HttpEntity entity, Map<String, Object> headers) throws Exception {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
StringBuilder stringBuffer = null;
try {
httpClient = defaultHttpClient(url);
HttpPost post = new HttpPost(url);
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/json;charset=UTF-8");
if (headers.size() > 0) {
for (Map.Entry<String, Object> header : headers.entrySet()) {
post.setHeader(header.getKey(), String.valueOf(header.getValue()));
}
}
//超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000).setConnectionRequestTimeout(5000)
.setSocketTimeout(5000).build();
post.setConfig(requestConfig);
if (entity != null) {
post.setEntity(entity);
}
response = httpClient.execute(post);
stringBuffer = getResult(response.getEntity());
} catch (Exception e) {
logger.error("", e);
} finally {
if (null != httpClient)
httpClient.close();
if (null != response)
response.close();
}
return stringBuffer;
}
public static StringEntity createJsonEntity(Object data) throws JsonProcessingException, UnsupportedEncodingException {
return new StringEntity(mapper.writeValueAsString(data));
}
public static UrlEncodedFormEntity createFormEntity(Map<String, Object> data) throws UnsupportedEncodingException {
List<NameValuePair> pairs = new ArrayList<>();
for (Map.Entry<String, Object> entry : data.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
return new UrlEncodedFormEntity(pairs);
}
public static Map<String, Object> createFormHeader() throws UnsupportedEncodingException {
Map<String, Object> headers = new HashMap<>();
headers.put("Accept", "*/*");
headers.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
return headers;
}
private static StringBuilder getResult(HttpEntity entity) throws IOException {
StringBuilder stringBuffer = null;
if (null != entity) {
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
stringBuffer = new StringBuilder();
String str = "";
while ((str = br.readLine()) != null)
stringBuffer.append(str);
}
return stringBuffer;
}
}