1 packagecom.test;2
3 importjava.io.File;4 importjava.io.IOException;5 importjava.security.KeyManagementException;6 importjava.security.KeyStoreException;7 importjava.security.NoSuchAlgorithmException;8 importjava.util.Iterator;9 importjava.util.List;10 importjava.util.Map;11
12 importorg.apache.http.HttpEntity;13 importorg.apache.http.HttpStatus;14 importorg.apache.http.client.config.RequestConfig;15 importorg.apache.http.client.methods.CloseableHttpResponse;16 importorg.apache.http.client.methods.HttpGet;17 importorg.apache.http.client.methods.HttpPost;18 importorg.apache.http.config.Registry;19 importorg.apache.http.config.RegistryBuilder;20 importorg.apache.http.conn.socket.ConnectionSocketFactory;21 importorg.apache.http.conn.socket.PlainConnectionSocketFactory;22 importorg.apache.http.conn.ssl.SSLConnectionSocketFactory;23 importorg.apache.http.conn.ssl.SSLContextBuilder;24 importorg.apache.http.conn.ssl.TrustSelfSignedStrategy;25 importorg.apache.http.entity.ContentType;26 importorg.apache.http.entity.StringEntity;27 importorg.apache.http.entity.mime.MultipartEntityBuilder;28 importorg.apache.http.entity.mime.content.FileBody;29 importorg.apache.http.entity.mime.content.StringBody;30 importorg.apache.http.impl.client.CloseableHttpClient;31 importorg.apache.http.impl.client.DefaultHttpRequestRetryHandler;32 importorg.apache.http.impl.client.HttpClients;33 importorg.apache.http.impl.conn.PoolingHttpClientConnectionManager;34 importorg.apache.http.util.EntityUtils;35
36 /**
37 *38 *@authorH__D39 * @date 2016年10月19日 上午11:27:2540 *41 */
42 public classHttpClientUtil {43
44 //utf-8字符编码
45 public static final String CHARSET_UTF_8 = "utf-8";46
47 //HTTP内容类型。
48 public static final String CONTENT_TYPE_TEXT_HTML = "text/xml";49
50 //HTTP内容类型。相当于form表单的形式,提交数据
51 public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";52
53 //HTTP内容类型。相当于form表单的形式,提交数据
54 public static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8";55
56
57 //连接管理器
58 private staticPoolingHttpClientConnectionManager pool;59
60 //请求配置
61 private staticRequestConfig requestConfig;62
63 static{64
65 try{66 //System.out.println("初始化HttpClientTest~~~开始");
67 SSLContextBuilder builder = newSSLContextBuilder();68 builder.loadTrustMaterial(null, newTrustSelfSignedStrategy());69 SSLConnectionSocketFactory sslsf = newSSLConnectionSocketFactory(70 builder.build());71 //配置同时支持 HTTP 和 HTPPS
72 Registry socketFactoryRegistry = RegistryBuilder.create().register(73 "http", PlainConnectionSocketFactory.getSocketFactory()).register(74 "https", sslsf).build();75 //初始化连接管理器
76 pool = newPoolingHttpClientConnectionManager(77 socketFactoryRegistry);78 //将最大连接数增加到200,实际项目最好从配置文件中读取这个值
79 pool.setMaxTotal(200);80 //设置最大路由
81 pool.setDefaultMaxPerRoute(2);82 //根据默认超时限制初始化requestConfig
83 int socketTimeout = 10000;84 int connectTimeout = 10000;85 int connectionRequestTimeout = 10000;86 requestConfig =RequestConfig.custom().setConnectionRequestTimeout(87 connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(88 connectTimeout).build();89
90 //System.out.println("初始化HttpClientTest~~~结束");
91 } catch(NoSuchAlgorithmException e) {92 e.printStackTrace();93 } catch(KeyStoreException e) {94 e.printStackTrace();95 } catch(KeyManagementException e) {96 e.printStackTrace();97 }98
99
100 //设置请求超时时间
101 requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000)102 .setConnectionRequestTimeout(50000).build();103 }104
105 public staticCloseableHttpClient getHttpClient() {106
107 CloseableHttpClient httpClient =HttpClients.custom()108 //设置连接池管理
109 .setConnectionManager(pool)110 //设置请求配置
111 .setDefaultRequestConfig(requestConfig)112 //设置重试次数
113 .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))114 .build();115
116 returnhttpClient;117 }118
119 /**
120 * 发送Post请求121 *122 *@paramhttpPost123 *@return
124 */
125 private staticString sendHttpPost(HttpPost httpPost) {126
127 CloseableHttpClient httpClient = null;128 CloseableHttpResponse response = null;129 //响应内容
130 String responseContent = null;131 try{132 //创建默认的httpClient实例.
133 httpClient =getHttpClient();134 //配置请求信息
135 httpPost.setConfig(requestConfig);136 //执行请求
137 response =httpClient.execute(httpPost);138 //得到响应实例
139 HttpEntity entity =response.getEntity();140
141 //可以获得响应头142 //Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);143 //for (Header header : headers) {144 //System.out.println(header.getName());145 //}146
147 //得到响应类型148 //System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());149
150 //判断响应状态
151 if (response.getStatusLine().getStatusCode() >= 300) {152 throw newException(153 "HTTP Request is not success, Response code is " +response.getStatusLine().getStatusCode());154 }155
156 if (HttpStatus.SC_OK ==response.getStatusLine().getStatusCode()) {157 responseContent =EntityUtils.toString(entity, CHARSET_UTF_8);158 EntityUtils.consume(entity);159 }160
161 } catch(Exception e) {162 e.printStackTrace();163 } finally{164 try{165 //释放资源
166 if (response != null) {167 response.close();168 }169 } catch(IOException e) {170 e.printStackTrace();171 }172 }173 returnresponseContent;174 }175
176 /**
177 * 发送Get请求178 *179 *@paramhttpGet180 *@return
181 */
182 private staticString sendHttpGet(HttpGet httpGet) {183
184 CloseableHttpClient httpClient = null;185 CloseableHttpResponse response = null;186 //响应内容
187 String responseContent = null;188 try{189 //创建默认的httpClient实例.
190 httpClient =getHttpClient();191 //配置请求信息
192 httpGet.setConfig(requestConfig);193 //执行请求
194 response =httpClient.execute(httpGet);195 //得到响应实例
196 HttpEntity entity =response.getEntity();197
198 //可以获得响应头199 //Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);200 //for (Header header : headers) {201 //System.out.println(header.getName());202 //}203
204 //得到响应类型205 //System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());206
207 //判断响应状态
208 if (response.getStatusLine().getStatusCode() >= 300) {209 throw newException(210 "HTTP Request is not success, Response code is " +response.getStatusLine().getStatusCode());211 }212
213 if (HttpStatus.SC_OK ==response.getStatusLine().getStatusCode()) {214 responseContent =EntityUtils.toString(entity, CHARSET_UTF_8);215 EntityUtils.consume(entity);216 }217
218 } catch(Exception e) {219 e.printStackTrace();220 } finally{221 try{222 //释放资源
223 if (response != null) {224 response.close();225 }226 } catch(IOException e) {227 e.printStackTrace();228 }229 }230 returnresponseContent;231 }232
233
234
235 /**
236 * 发送 post请求237 *238 *@paramhttpUrl239 * 地址240 */
241 public staticString sendHttpPost(String httpUrl) {242 //创建httpPost
243 HttpPost httpPost = newHttpPost(httpUrl);244 returnsendHttpPost(httpPost);245 }246
247 /**
248 * 发送 get请求249 *250 *@paramhttpUrl251 */
252 public staticString sendHttpGet(String httpUrl) {253 //创建get请求
254 HttpGet httpGet = newHttpGet(httpUrl);255 returnsendHttpGet(httpGet);256 }257
258
259
260 /**
261 * 发送 post请求(带文件)262 *263 *@paramhttpUrl264 * 地址265 *@parammaps266 * 参数267 *@paramfileLists268 * 附件269 */
270 public static String sendHttpPost(String httpUrl, Map maps, ListfileLists) {271 HttpPost httpPost = new HttpPost(httpUrl);//创建httpPost
272 MultipartEntityBuilder meBuilder =MultipartEntityBuilder.create();273 if (maps != null) {274 for(String key : maps.keySet()) {275 meBuilder.addPart(key, newStringBody(maps.get(key), ContentType.TEXT_PLAIN));276 }277 }278 if (fileLists != null) {279 for(File file : fileLists) {280 FileBody fileBody = newFileBody(file);281 meBuilder.addPart("files", fileBody);282 }283 }284 HttpEntity reqEntity =meBuilder.build();285 httpPost.setEntity(reqEntity);286 returnsendHttpPost(httpPost);287 }288
289 /**
290 * 发送 post请求291 *292 *@paramhttpUrl293 * 地址294 *@paramparams295 * 参数(格式:key1=value1&key2=value2)296 *297 */
298 public staticString sendHttpPost(String httpUrl, String params) {299 HttpPost httpPost = new HttpPost(httpUrl);//创建httpPost
300 try{301 //设置参数
302 if (params != null && params.trim().length() > 0) {303 StringEntity stringEntity = new StringEntity(params, "UTF-8");304 stringEntity.setContentType(CONTENT_TYPE_FORM_URL);305 httpPost.setEntity(stringEntity);306 }307 } catch(Exception e) {308 e.printStackTrace();309 }310 returnsendHttpPost(httpPost);311 }312
313 /**
314 * 发送 post请求315 *316 *@parammaps317 * 参数318 */
319 public static String sendHttpPost(String httpUrl, Mapmaps) {320 String parem =convertStringParamter(maps);321 returnsendHttpPost(httpUrl, parem);322 }323
324
325
326
327 /**
328 * 发送 post请求 发送json数据329 *330 *@paramhttpUrl331 * 地址332 *@paramparamsJson333 * 参数(格式 json)334 *335 */
336 public staticString sendHttpPostJson(String httpUrl, String paramsJson) {337 HttpPost httpPost = new HttpPost(httpUrl);//创建httpPost
338 try{339 //设置参数
340 if (paramsJson != null && paramsJson.trim().length() > 0) {341 StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8");342 stringEntity.setContentType(CONTENT_TYPE_JSON_URL);343 httpPost.setEntity(stringEntity);344 }345 } catch(Exception e) {346 e.printStackTrace();347 }348 returnsendHttpPost(httpPost);349 }350
351 /**
352 * 发送 post请求 发送xml数据353 *354 *@paramhttpUrl 地址355 *@paramparamsXml 参数(格式 Xml)356 *357 */
358 public staticString sendHttpPostXml(String httpUrl, String paramsXml) {359 HttpPost httpPost = new HttpPost(httpUrl);//创建httpPost
360 try{361 //设置参数
362 if (paramsXml != null && paramsXml.trim().length() > 0) {363 StringEntity stringEntity = new StringEntity(paramsXml, "UTF-8");364 stringEntity.setContentType(CONTENT_TYPE_TEXT_HTML);365 httpPost.setEntity(stringEntity);366 }367 } catch(Exception e) {368 e.printStackTrace();369 }370 returnsendHttpPost(httpPost);371 }372
373
374 /**
375 * 将map集合的键值对转化成:key1=value1&key2=value2 的形式376 *377 *@paramparameterMap378 * 需要转化的键值对集合379 *@return字符串380 */
381 public staticString convertStringParamter(Map parameterMap) {382 StringBuffer parameterBuffer = newStringBuffer();383 if (parameterMap != null) {384 Iterator iterator =parameterMap.keySet().iterator();385 String key = null;386 String value = null;387 while(iterator.hasNext()) {388 key =(String) iterator.next();389 if (parameterMap.get(key) != null) {390 value =(String) parameterMap.get(key);391 } else{392 value = "";393 }394 parameterBuffer.append(key).append("=").append(value);395 if(iterator.hasNext()) {396 parameterBuffer.append("&");397 }398 }399 }400 returnparameterBuffer.toString();401 }402
403 public static void main(String[] args) throwsException {404
405 System.out.println(sendHttpGet("http://www.baidu.com"));406
407 }408 }