Share a httpclient tool class written by yourself

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 tool class
 */
public class HttpKit {
	
	/**   
	 * Encapsulate the result returned by the http request
	 */
	public static class ResponseResult{
		
		//Network status code
		private int    statusCode  = -1;
		//contentType of the response result
		private String contentType = null;
		//response result string
		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); //The maximum number of connections in the connection pool
	    cm.setDefaultMaxPerRoute(60); //The maximum number of routes, that is, the number of connections that each domain name domain can use, the default is 2
	    rc = RequestConfig.custom().setConnectTimeout(5 * 1000) // request timeout
	        .setSocketTimeout(60 * 1000) // Waiting for data timeout, that is, this http connection can send multiple requests to the target server during this time period
	        .setConnectionRequestTimeout(1000) // The connection pool waits for the timeout time. If this time is not set, it will wait all the time, which may cause thread blockage
	        .build();
	}
	
	private HttpKit(){}

	/**
	 * Get HttpClient through connection pool
	 */
	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);
	}

	/**Initiate a request through get
	 * @param url request address
	 * @param headers request header
	 * @param params request parameters
	 * @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);
	}

	/**Initiate the request by post
	 * @param url request address
	 * @param headers request header
	 * @param params request parameters
	 * @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("An exception occurred when initiating an http request, the target address ["+request.getURI()+"]", e);
		}finally{
			consume(entity);
		}
	}
	
	private static void consume(HttpEntity entity){
		try {
			EntityUtils.consume(entity);
		} catch (IOException e) {
			log.error("An exception occurred when releasing the http connection", e);
		}
	}
	
}

 httpclient version 4.41, if there are any shortcomings, please advise

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326288228&siteId=291194637