分享一个自己 写的httpclient工具类

package com.fastwork.bm.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;





/**   
 * @description Http工具类
 */
public class HttpKit {
	
	/**   
	 * 封装http请求返回的结果
	 */
	public static class ResponseResult{
		
		//网络状态码
		private int    statusCode  = -1;
		//响应结果的contentType
		private String contentType = null;
		//响应结果字符串
		private String body		   = null;

		public ResponseResult(int statusCode, String contentType, String body) {
			this.statusCode = statusCode;
			this.contentType = contentType;
			this.body = body;
		}

		public int getStatusCode() {
			return statusCode;
		}

		public void setStatusCode(int statusCode) {
			this.statusCode = statusCode;
		}

		public String getContentType() {
			return contentType;
		}

		public void setContentType(String contentType) {
			this.contentType = contentType;
		}

		public String getBody() {
			return body;
		}

		public void setBody(String body) {
			this.body = body;
		}
		
		
	}
	
	private static Logger log = Logger.getLogger(HttpKit.class);
	
	private static PoolingHttpClientConnectionManager cm = null;
	
	private static RequestConfig 					  rc = null;
	
	private static final String ENCODING = "UTF-8";
	
	static {
		cm = new PoolingHttpClientConnectionManager();
	    cm.setMaxTotal(300); 				   //连接池最大连接数
	    cm.setDefaultMaxPerRoute(60);		   //最大路由数,即每个域名domain可以使用的连接数,默认2
	    rc = RequestConfig.custom().setConnectTimeout(5 * 1000) // 请求超时时间
	        .setSocketTimeout(60 * 1000)        // 等待数据超时时间,即在该时间段内此http连接可向目标服务器发送多个请求
	        .setConnectionRequestTimeout(1000)  // 连接池等待超时时间,如不设置该时间将一直等待,可能造成线程堵塞
	        .build();
	}
	
	private HttpKit(){}

	/**
	 * 通过连接池获取HttpClient
	 */
	private static CloseableHttpClient getHttpClient() {
		return HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(rc).build();
	}

	public static ResponseResult get(String url) {
		return get(url,null,null);
	}

	public static ResponseResult get(String url, Map<String, Object> params) {
		return get(url,params,null);
	}

	/**通过get方式发起请求
	 * @param url     请求地址
	 * @param headers 请求头
	 * @param params  请求参数
	 * @return
	 */
	public static ResponseResult get(String url, Map<String, Object> headers, Map<String, Object> params)  {
		URIBuilder ub = new URIBuilder().setPath(url);
		if(params != null){
			ub.setParameters(covertParams2NVPS(params));
		}
		try {
			HttpGet httpGet = new HttpGet(ub.build());
			if(headers != null){
				for (Map.Entry<String, Object> header : headers.entrySet()) {
					httpGet.addHeader(header.getKey(), String.valueOf(header.getValue()));
				}
			}
			return getResult(httpGet);
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	
	}

	public static ResponseResult post(String url) {
		return post(url,null,null);
	}

	public static ResponseResult post(String url, Map<String, Object> params)  {
		return post(url,params,null);
	}

	/**通过post方式发起请求
	 * @param url     请求地址
	 * @param headers 请求头
	 * @param params  请求参数
	 * @return
	 */
	public static ResponseResult post(String url, Map<String, Object> headers, Map<String, Object> params) {
		URIBuilder ub = new URIBuilder().setPath(url);
		try {
			HttpPost httpPost = new HttpPost(ub.build());
			if(params  != null){
				httpPost.setEntity(new UrlEncodedFormEntity(covertParams2NVPS(params), ENCODING));
			}
			if(headers != null){
				for (Map.Entry<String, Object> header : headers.entrySet()) {
					httpPost.addHeader(header.getKey(), String.valueOf(header.getValue()));
				}
			}
			return getResult(httpPost);
		} catch (URISyntaxException | UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		} 
	}

	private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
		ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
		for (Map.Entry<String, Object> param : params.entrySet()) {
			pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
		}
		return pairs;
	}

	private static ResponseResult getResult(HttpRequestBase request) {
		HttpEntity entity 			   = null;
		CloseableHttpClient httpClient = getHttpClient();
		try(CloseableHttpResponse response = httpClient.execute(request)){
		    entity = response.getEntity();
			return new ResponseResult(
					response.getStatusLine().getStatusCode(),
					entity.getContentType().getValue(),
					EntityUtils.toString(entity,ENCODING));
		} catch (IOException e) {
			throw new RuntimeException("发起http请求的时候发生异常,目标地址["+request.getURI()+"]", e);
		}finally{
			consume(entity);
		}
	}
	
	private static void consume(HttpEntity entity){
		try {
			EntityUtils.consume(entity);
		} catch (IOException e) {
			log.error("释放http连接的时候发生异常", e);
		}
	}
	
}

 httpclient 版本 4.41,如有不足处请多多指教

猜你喜欢

转载自wangning1125.iteye.com/blog/2409140