java httpclient封装类_基于httpclient的一些常用方法封装

这个博客介绍了如何使用Java实现一个基于HttpClient的工具类,包括GET、POST、PUT和DELETE等HTTP方法的封装,支持HTTP和HTTPS请求,并且包含了SSL证书的信任管理。该工具类提供了设置超时、请求头和请求参数等功能,方便进行HTTP请求操作。
摘要由CSDN通过智能技术生成

1 packagecom.util;2

3 importjava.io.IOException;4 importjava.io.UnsupportedEncodingException;5 importjava.security.cert.CertificateException;6 importjava.security.cert.X509Certificate;7 importjava.util.ArrayList;8 importjava.util.HashMap;9 importjava.util.List;10 importjava.util.Map;11 importjava.util.Map.Entry;12 importjava.util.Set;13

14 importjavax.net.ssl.SSLContext;15 importjavax.net.ssl.TrustManager;16 importjavax.net.ssl.X509TrustManager;17

18 importorg.apache.commons.collections.MapUtils;19 importorg.apache.http.HttpStatus;20 importorg.apache.http.NameValuePair;21 importorg.apache.http.client.config.RequestConfig;22 importorg.apache.http.client.entity.UrlEncodedFormEntity;23 importorg.apache.http.client.methods.CloseableHttpResponse;24 importorg.apache.http.client.methods.HttpDelete;25 importorg.apache.http.client.methods.HttpEntityEnclosingRequestBase;26 importorg.apache.http.client.methods.HttpGet;27 importorg.apache.http.client.methods.HttpPost;28 importorg.apache.http.client.methods.HttpPut;29 importorg.apache.http.client.methods.HttpRequestBase;30 importorg.apache.http.client.utils.URIBuilder;31 importorg.apache.http.config.Registry;32 importorg.apache.http.config.RegistryBuilder;33 importorg.apache.http.conn.socket.ConnectionSocketFactory;34 importorg.apache.http.conn.socket.PlainConnectionSocketFactory;35 importorg.apache.http.conn.ssl.SSLConnectionSocketFactory;36 importorg.apache.http.entity.StringEntity;37 importorg.apache.http.impl.client.CloseableHttpClient;38 importorg.apache.http.impl.client.HttpClientBuilder;39 importorg.apache.http.impl.conn.PoolingHttpClientConnectionManager;40 importorg.apache.http.message.BasicNameValuePair;41 importorg.apache.http.util.EntityUtils;42

43 /**

44 * commons-httpclient(停更)与httpclient(继续升级中)45 *46 * HTTP连接池请求,支持http和https请求,47 *

48 * 基于org.apache.httpcomponents.httpcore4.4.1049 *

50 *

51 * 基于org.apache.httpcomponents.httpclient4.5.652 *

53 *54 *@authorHenry(fba02)55 *@version[版本号, 2019年12月8日]56 *@see[相关类/方法]57 *@since[产品/模块版本]58 */

59 public classHttpClientPoolUtil {60 private static final String ENCODING = "UTF-8";61 public static final int DEFAULT_CONNECT_TIMEOUT = 6000;62 public static final int DEFAULT_READ_TIMEOUT = 6000;63 public static final int DEFAULT_CONNECT_REQUEST_TIMEOUT = 6000;64 private static final int MAX_TOTAL = 64;65 private static final int MAX_PER_ROUTE = 32;66 private static finalRequestConfig requestConfig;67 private static finalPoolingHttpClientConnectionManager connectionManager;68 private static finalHttpClientBuilder httpBuilder;69 private static finalCloseableHttpClient httpClient;70 private static finalCloseableHttpClient httpsClient;71 private staticSSLContext sslContext;72

73 static{74 try{75 sslContext = SSLContext.getInstance("TLS");76 X509TrustManager tm = newX509TrustManager() {77 @Override78 public voidcheckClientTrusted(X509Certificate[] chain, String authType)79 throwsCertificateException {80 }81 @Override82 public voidcheckServerTrusted(X509Certificate[] chain, String authType)83 throwsCertificateException {84 }85 @Override86 publicX509Certificate[] getAcceptedIssuers() {87 return null;88 }89 };90 sslContext.init(null, new TrustManager[] {tm}, null);91 } catch(Exception e) {92 e.printStackTrace();93 }94 }95

96 static{97 requestConfig =RequestConfig.custom().setSocketTimeout(DEFAULT_READ_TIMEOUT).setConnectTimeout(DEFAULT_CONNECT_TIMEOUT).setConnectionRequestTimeout(DEFAULT_CONNECT_REQUEST_TIMEOUT).build();98 @SuppressWarnings("deprecation")99 Registry socketFactoryRegistry = RegistryBuilder.create()100 .register("http", newPlainConnectionSocketFactory())101 .register("https", newSSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))102 .build();103 connectionManager = newPoolingHttpClientConnectionManager(socketFactoryRegistry);104 connectionManager.setMaxTotal(MAX_TOTAL);105 connectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);106 httpBuilder =HttpClientBuilder.create();107 httpBuilder.setDefaultRequestConfig(requestConfig);108 httpBuilder.setConnectionManager(connectionManager);109 httpClient =httpBuilder.build();110 httpsClient =httpBuilder.build();111 }112

113 /**

114 * GET115 *116 *@paramurl117 *@return

118 *@throwsException119 *@authorHenry(fba02)120 *@version[版本号, 2019年12月8日]121 *@see[类、类#方法、类#成员]122 */

123 public staticHttpClientResult doGet(String url)124 throwsException {125 return doGet(url, false);126 }127

128 /**

129 * GET130 *131 *@paramurl132 *@paramhttps133 *@return

134 *@throwsException135 *@authorHenry(fba02)136 *@version[版本号, 2019年12月8日]137 *@see[类、类#方法、类#成员]138 */

139 public static HttpClientResult doGet(String url, booleanhttps)140 throwsException {141 return doGet(url, null, null, https);142 }143

144 /**

145 * GET146 *147 *@paramurl148 *@paramparams149 *@paramhttps150 *@return

151 *@throwsException152 *@authorHenry(fba02)153 *@version[版本号, 2019年12月8日]154 *@see[类、类#方法、类#成员]155 */

156 public static HttpClientResult doGet(String url, Map params, booleanhttps)157 throwsException {158 return doGet(url, null, params, https);159 }160

161 /**

162 * GET163 *164 *@paramurl165 *@paramheaders166 *@paramparams167 *@paramhttps168 *@return

169 *@throwsException170 *@authorHenry(fba02)171 *@version[版本号, 2019年12月8日]172 *@see[类、类#方法、类#成员]173 */

174 public static HttpClientResult doGet(String url, Map headers, Map params, booleanhttps)175 throwsException {176 //创建访问的地址

177 URIBuilder uriBuilder = newURIBuilder(url);178 if (params != null) {179 Set> entrySet =params.entrySet();180 for (Entryentry : entrySet) {181 uriBuilder.setParameter(entry.getKey(), entry.getValue());182 }183 }184 //创建HTTP对象

185 HttpGet httpGet = newHttpGet(uriBuilder.build());186 httpGet.setConfig(requestConfig);187 //设置请求头

188 setHeader(headers, httpGet);189 //创建httpResponse对象

190 CloseableHttpResponse httpResponse = null;191 try{192 if(https) {193 returngetHttpClientResult(httpResponse, httpsClient, httpGet);194 } else{195 returngetHttpClientResult(httpResponse, httpClient, httpGet);196 }197 } finally{198 httpGet.releaseConnection();199 release(httpResponse);200 }201 }202

203 /**

204 * POST不带参数205 *206 *@paramurl207 *@return

208 *@throwsException209 *@authorHenry(fba02)210 *@version[版本号, 2019年12月8日]211 *@see[类、类#方法、类#成员]212 */

213 public staticHttpClientResult doPost(String url)214 throwsException {215 returndoPost(url, Boolean.FALSE);216 }217

218 /**

219 *@paramurl220 *@paramhttps221 *@return

222 *@throwsException223 *@authorHenry(fba02)224 *@version[版本号, 2019年12月8日]225 *@see[类、类#方法、类#成员]226 */

227 public static HttpClientResult doPost(String url, booleanhttps)228 throwsException {229 return doPost(url, null, (Map)null, https);230 }231

232 /**

233 * 带请求参数234 *235 *@paramurl236 *@paramparams237 *@paramhttps238 *@return

239 *@throwsException240 *@authorHenry(fba02)241 *@version[版本号, 2019年12月8日]242 *@see[类、类#方法、类#成员]243 */

244 public static HttpClientResult doPost(String url, Map params, booleanhttps)245 throwsException {246 return doPost(url, null, params, https);247 }248

249 /**

250 * POST251 *252 *@paramurl253 *@paramheaders254 *@paramparams255 *@paramhttps256 *@return

257 *@throwsException258 *@authorHenry(fba02)259 *@version[版本号, 2019年12月8日]260 *@see[类、类#方法、类#成员]261 */

262 public static HttpClientResult doPost(String url, Map headers, Map params, booleanhttps)263 throwsException {264 //创建HTTP对象

265 HttpPost httpPost = newHttpPost(url);266 httpPost.setConfig(requestConfig);267 //设置请求头

268 setHeader(headers, httpPost);269 //封装请求参数

270 setParam(params, httpPost);271 //创建httpResponse对象

272 CloseableHttpResponse httpResponse = null;273 try{274 if(https) {275 returngetHttpClientResult(httpResponse, httpsClient, httpPost);276 } else{277 returngetHttpClientResult(httpResponse, httpClient, httpPost);278 }279 } finally{280 httpPost.releaseConnection();281 release(httpResponse);282 }283 }284

285 /**

286 * POST请求JSON287 *288 *@paramurl289 *@paramheaders290 *@paramjson291 *@paramhttps292 *@return

293 *@throwsException294 *@authorHenry(fba02)295 *@version[版本号, 2019年12月8日]296 *@see[类、类#方法、类#成员]297 */

298 public static HttpClientResult doPost(String url, Map headers, String json, booleanhttps)299 throwsException {300 //创建HTTP对象

301 HttpPost httpPost = newHttpPost(url);302 httpPost.setConfig(requestConfig);303 //设置请求头

304 setHeader(headers, httpPost);305 StringEntity stringEntity = newStringEntity(json, ENCODING);306 stringEntity.setContentEncoding(ENCODING);307 httpPost.setEntity(stringEntity);308 //创建httpResponse对象

309 CloseableHttpResponse httpResponse = null;310 try{311 if(https) {312 returngetHttpClientResult(httpResponse, httpsClient, httpPost);313 } else{314 returngetHttpClientResult(httpResponse, httpClient, httpPost);315 }316 } finally{317 httpPost.releaseConnection();318 release(httpResponse);319 }320 }321

322

323 /**

324 * 发送put请求;不带请求参数325 *326 *@paramurl 请求地址327 *@paramparams 参数集合328 *@return

329 *@throwsException330 */

331 public staticHttpClientResult doPut(String url)332 throwsException {333 returndoPut(url);334 }335

336 /**

337 * 发送put请求;带请求参数338 *339 *@paramurl 请求地址340 *@paramparams 参数集合341 *@return

342 *@throwsException343 */

344 public static HttpClientResult doPut(String url, Mapparams)345 throwsException {346 //CloseableHttpClient httpClient = HttpClients.createDefault();

347 HttpPut httpPut = newHttpPut(url);348 //RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();

349 httpPut.setConfig(requestConfig);350 setParam(params, httpPut);351 CloseableHttpResponse httpResponse = null;352 try{353 returngetHttpClientResult(httpResponse, httpClient, httpPut);354 } finally{355 httpPut.releaseConnection();356 release(httpResponse);357 }358 }359

360 /**

361 * 不带请求参数362 *363 *@paramurl364 *@return

365 *@throwsException366 *@authorHenry(fba02)367 *@version[版本号, 2019年12月8日]368 *@see[类、类#方法、类#成员]369 */

370 public staticHttpClientResult doDelete(String url)371 throwsException {372 //CloseableHttpClient httpClient = HttpClients.createDefault();

373 HttpDelete httpDelete = newHttpDelete(url);374 //RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();

375 httpDelete.setConfig(requestConfig);376 CloseableHttpResponse httpResponse = null;377 try{378 returngetHttpClientResult(httpResponse, httpClient, httpDelete);379 } finally{380 httpDelete.releaseConnection();381 release(httpResponse);382 }383 }384

385 /**

386 * 带请求参数387 *388 *@paramurl389 *@paramparams390 *@paramhttps391 *@return

392 *@throwsException393 *@authorHenry(fba02)394 *@version[版本号, 2019年12月8日]395 *@see[类、类#方法、类#成员]396 */

397 public static HttpClientResult doDelete(String url, Map params, booleanhttps)398 throwsException {399 if (params == null) {400 params = new HashMap();401 }402 params.put("_method", "delete");403 returndoPost(url, params, https);404 }405

406 /**

407 * 设置封装请求头408 *409 *@paramparams410 *@paramhttpMethod411 *@authorHenry(fba02)412 *@version[版本号, 2019年12月8日]413 *@see[类、类#方法、类#成员]414 */

415 public static void setHeader(Mapparams, HttpRequestBase httpMethod) {416 //封装请求头

417 if(MapUtils.isNotEmpty(params)) {418 Set> entrySet =params.entrySet();419 for (Entryentry : entrySet) {420 //设置到请求头到HttpRequestBase对象中

421 httpMethod.setHeader(entry.getKey(), entry.getValue());422 }423 }424 }425

426 /**

427 * 封装请求参数428 *429 *@paramparams430 *@paramhttpMethod431 *@throwsUnsupportedEncodingException432 *@authorHenry(fba02)433 *@version[版本号, 2019年12月8日]434 *@see[类、类#方法、类#成员]435 */

436 public static void setParam(Mapparams, HttpEntityEnclosingRequestBase httpMethod)437 throwsUnsupportedEncodingException {438 //封装请求参数

439 if(MapUtils.isNotEmpty(params)) {440 List nvps = new ArrayList();441 Set> entrySet =params.entrySet();442 for (Entryentry : entrySet) {443 nvps.add(newBasicNameValuePair(entry.getKey(), entry.getValue()));444 }445 //设置到请求的http对象中

446 httpMethod.setEntity(newUrlEncodedFormEntity(nvps, ENCODING));447 }448 }449

450 /**

451 * 获得响应结果452 *453 *@paramhttpResponse454 *@paramhttpClient455 *@paramhttpMethod456 *@return

457 *@throwsException458 *@authorHenry(fba02)459 *@version[版本号, 2019年12月8日]460 *@see[类、类#方法、类#成员]461 */

462 public staticHttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient, HttpRequestBase httpMethod)463 throwsException {464 //执行请求

465 httpResponse =httpClient.execute(httpMethod);466 //获取返回结果

467 if (httpResponse != null && httpResponse.getStatusLine() != null) {468 String content = "";469 if (httpResponse.getEntity() != null) {470 content =EntityUtils.toString(httpResponse.getEntity(), ENCODING);471 }472 return newHttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);473 }474 return newHttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);475 }476

477 /**

478 * 释放资源479 *480 *@paramhttpResponse481 *@throwsIOException482 *@authorHenry(fba02)483 *@version[版本号, 2019年12月8日]484 *@see[类、类#方法、类#成员]485 */

486 public static voidrelease(CloseableHttpResponse httpResponse)487 throwsIOException {488 //释放资源

489 if (httpResponse != null) {490 httpResponse.close();491 }492 }493 }494

495 packagecom.util;496

497 importjava.io.Serializable;498

499 @SuppressWarnings("serial")500 public class HttpClientResult implementsSerializable {501 /**

502 * 响应状态码503 */

504 private intcode;505

506 /**

507 * 响应数据508 */

509 privateString content;510

511 public intgetCode() {512 returncode;513 }514

515 public void setCode(intcode) {516 this.code =code;517 }518

519 publicString getContent() {520 returncontent;521 }522

523 public voidsetContent(String content) {524 this.content =content;525 }526

527 publicHttpClientResult() {528 super();529 }530

531 public HttpClientResult(intcode) {532 super();533 this.code =code;534 }535

536 public HttpClientResult(intcode, String content) {537 super();538 this.code =code;539 this.content =content;540 }541

542 @Override543 publicString toString() {544 return "HttpClientResult [code=" + code + ", content=" + content + "]";545 }546 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值