HttpUtils(JAVA)


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.entity.StringEntity;
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.AbstractHttpMessage;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class HttpUtils {

	protected static Log logger = LogFactory.getLog(HttpUtils.class);

	private static PoolingHttpClientConnectionManager cm;
	private static String EMPTY_STR = "";
	private static String UTF_8 = "UTF-8";
	private static RequestConfig requestConfig;
	private static final int CONNECT_TIMEOUT = 600000; //设置连接超时时间,单位毫秒。
	private static final int CONNECTION_REQUEST_TIMEOUT = 5000; //设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
	private static final int SOCKET_TIMEOUT = 600000; //请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。

	/**
	 * 初始化,很多人喜欢使用懒加载,在使用的时候再进行初始化,我个人认为,已经确定要用的资源,最好启动的时候就加载
	 * 即使会慢一点,也比中途出现突然的加载加压好一点,而且如果有问题也能提前曝出,不会等着真正要用的时候,才开始
	 * 邹眉头
	 */
	private static void init() {
		cm = new PoolingHttpClientConnectionManager();
		cm.setMaxTotal(10);// 整个连接池最大连接数
		cm.setDefaultMaxPerRoute(5);// 每路由最大连接数,默认值是2

		//请求配置
		//   setConnectTimeout:设置连接超时时间,单位毫秒。
		//	 setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
		//	 setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
		requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
				.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();

	}

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

	public static String httpGetRequest(String url) {
		HttpGet httpGet = new HttpGet(url);
		return getResult(httpGet);
	}

	public static String httpGetRequest(String url, Map params) throws URISyntaxException {
		return httpGetRequest(url,null,params);
	}

	public static String httpGetRequest(String url, Map headers, Map params)
			throws URISyntaxException {
		URIBuilder ub = new URIBuilder();
		ub.setPath(url);
		ArrayList pairs = covertParams2NVPS(params);
		ub.setParameters(pairs);

		HttpGet httpGet = new HttpGet(ub.build());
		setHttpHeader(httpGet,headers);

		return getResult(httpGet);
	}

	public static String httpPostRequest(String url) {
		HttpPost httpPost = new HttpPost(url);
		return getResult(httpPost);
	}

	public static String httpPostRequest(String url, Map params) throws UnsupportedEncodingException {
		return httpPostRequest(url,null,params);
	}

	public static String httpPostRequest(String url, Map headers, Map params)
			throws UnsupportedEncodingException {
		HttpPost httpPost = new HttpPost(url);
		setHttpHeader(httpPost,headers);

		ArrayList pairs = covertParams2NVPS(params);
		httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));

		return getResult(httpPost);
	}

	public static String httpPostRequest(String url, Map headers, String strBody)
			throws Exception {
		HttpPost httpPost = new HttpPost(url);
		setHttpHeader(httpPost,headers);

		httpPost.setEntity(new StringEntity(strBody, UTF_8));
		return getResult(httpPost);
	}

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

		return pairs;
	}

	/**
	 * 处理Http请求
	 *
	 * setConnectTimeout:设置连接超时时间,单位毫秒。
	 * setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
	 * setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
	 *
	 * @param request
	 * @return
	 */
	private static String getResult(HttpRequestBase request) {

		request.setConfig(requestConfig);// 设置请求和传输超时时间

		// CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpClient httpClient = getHttpClient();
		try {
			CloseableHttpResponse response = httpClient.execute(request); //执行请求
			// response.getStatusLine().getStatusCode();
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				// long len = entity.getContentLength();// -1 表示长度未知
				String result = EntityUtils.toString(entity);
				response.close();
				// httpClient.close();
				return result;
			}
		} catch (ClientProtocolException e) {
			logger.error("[maperror] HttpClientUtil ClientProtocolException : " + e.getMessage());
			throw new RuntimeException( "HttpClientUtil IOException :" +e.getMessage());
		} catch (IOException e) {
			logger.error("[maperror] HttpClientUtil IOException : " + e.getMessage());
			throw new RuntimeException( "HttpClientUtil IOException :" + e.getMessage());
		} finally {

		}
		return EMPTY_STR;
	}

	/**
	 * 设置对象头
	 *
	 * @param http
	 * @param headers
	 */
	public static void setHttpHeader(AbstractHttpMessage http, Map headers) {
		if (isEmpty(headers)) {
			return;
		}
		headers.entrySet().stream().forEach(entry -> {
			String key = entry.getKey();
			String value = String.valueOf(entry.getValue());
			http.addHeader(new BasicHeader(key, value));
		});
	}

	/**
	 * 判断Map是否为空
	 *
	 * @param map
	 * @return null 或者 size = 0 返回true, 其他返回false
	 */
	public static boolean isEmpty(Map map) {
		return null == map || map.size() == 0;
	}

	public static void main(String[] args) throws URISyntaxException {
		Map params = new HashMap<>();
		params.put("t","1");
		params.put("k","%u6B7B%u795E");
		System.out.println(HttpUtils.httpGetRequest("https://b.faloo.com/l/0/1.html",params,params));
	}

}

 

你可能感兴趣的:(java基础)