HttpClientUtils.java 10.9 KB
package com.mass.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
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.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpClientUtils {


	/**
	 * 发送post请求
	 *
	 * @param url:请求地址
	 * @param header:请求头参数
	 * @param params:表单参数  form提交
	 * @param httpEntity   json/xml参数
	 * @return
	 */
	public static String doPostRequest(String url, Map<String, String> header, Map<String, String> params, HttpEntity httpEntity) {
		String resultStr = "";
		if (StringUtils.isEmpty(url)) {
			return resultStr;
		}
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse httpResponse = null;
		try {
			httpClient = SSLClientCustom.getHttpClinet();
			HttpPost httpPost = new HttpPost(url);
			//请求头header信息
			if (MapUtils.isNotEmpty(header)) {
				for (Map.Entry<String, String> stringStringEntry : header.entrySet()) {
					httpPost.setHeader(stringStringEntry.getKey(), stringStringEntry.getValue());
					log.info("请求header信息,key:{},value:{}", stringStringEntry.getKey(), stringStringEntry.getValue());
				}
			}
			//请求参数信息
			if (MapUtils.isNotEmpty(params)) {
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for (Map.Entry<String, String> stringStringEntry : params.entrySet()) {
					paramList.add(new BasicNameValuePair(stringStringEntry.getKey(), stringStringEntry.getValue()));
					log.info("请求参数信息,key:{},value:{}", stringStringEntry.getKey(), stringStringEntry.getValue());
				}
				UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
				httpPost.setEntity(urlEncodedFormEntity);
			}
			//实体设置
			if (httpEntity != null) {
				String json = EntityUtils.toString(httpEntity);
				log.info("请求参数信息{}", json);
				httpPost.setEntity(httpEntity);
			}
//			httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
			//发起请求
			httpResponse = httpClient.execute(httpPost);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK||statusCode == HttpStatus.SC_UNAUTHORIZED) {
				HttpEntity httpResponseEntity = httpResponse.getEntity();
				resultStr = EntityUtils.toString(httpResponseEntity);
				//log.info("请求正常,请求地址:{},响应结果:{}", url, statusCode+";"+resultStr);
			} else {
				StringBuffer stringBuffer = new StringBuffer();
				HeaderIterator headerIterator = httpResponse.headerIterator();
				while (headerIterator.hasNext()) {
					stringBuffer.append("\t" + headerIterator.next());
				}
				log.info("异常信息:请求地址:{},响应状态和结果:{}",url,statusCode+";"+stringBuffer);
			}

		} catch (Exception e) {
			log.info("请求地址:{}", url);
			e.printStackTrace();
		} finally {
			HttpClientUtils.closeConnection(httpClient, httpResponse);
		}
		return resultStr;
	}

	public static String doGetRequest(String url, Map<String, String> header, Map<String, Object> params) {
		String resultStr = "";
		if (StringUtils.isEmpty(url)) {
			return resultStr;
		}
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse httpResponse = null;
		try {
			httpClient = SSLClientCustom.getHttpClinet();
			//请求参数信息
			if (MapUtils.isNotEmpty(params)) {
				url = url + buildUrl(params);
			}
			HttpGet httpGet = new HttpGet(url);
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)//连接超时
					.setConnectionRequestTimeout(25000)//请求超时
					.setSocketTimeout(25000)//套接字连接超时
					.setRedirectsEnabled(true).build();//允许重定向
			httpGet.setConfig(requestConfig);
			if (MapUtils.isNotEmpty(header)) {
				for (Map.Entry<String, String> stringStringEntry : header.entrySet()) {
					httpGet.setHeader(stringStringEntry.getKey(), stringStringEntry.getValue());
				}
			}
			//发起请求
			httpResponse = httpClient.execute(httpGet);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				resultStr = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
				log.info("请求地址:{},响应结果:{}", url, resultStr);
			} else {
				StringBuffer stringBuffer = new StringBuffer();
				HeaderIterator headerIterator = httpResponse.headerIterator();
				while (headerIterator.hasNext()) {
					stringBuffer.append("\t" + headerIterator.next());
				}
				resultStr = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
				log.info("异常信息请求地址:{}", url, resultStr);
				log.info("异常信息:请求响应状态:{},请求返回结果:{}", httpResponse.getStatusLine().getStatusCode(),StringUtils.isBlank(resultStr)?stringBuffer:resultStr);
			}

		} catch (Exception e) {
			log.info("请求地址:{}", url);
			e.printStackTrace();

		} finally {
			HttpClientUtils.closeConnection(httpClient, httpResponse);
		}
		return resultStr;
	}

	public static String doGetRequest(String url, Map<String, String> header, Map<String, Object> params,StringBuffer tracecode) {
		String resultStr = "";
		if (StringUtils.isEmpty(url)) {
			return resultStr;
		}
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse httpResponse = null;
		try {
			httpClient = SSLClientCustom.getHttpClinet();
			//请求参数信息
			if (MapUtils.isNotEmpty(params)) {
				url = url + buildUrl(params);
			}
			HttpGet httpGet = new HttpGet(url);
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000)//连接超时
					.setConnectionRequestTimeout(30000)//请求超时
					.setSocketTimeout(30000)//套接字连接超时
					.setRedirectsEnabled(true).build();//允许重定向
			httpGet.setConfig(requestConfig);
			if (MapUtils.isNotEmpty(header)) {
				for (Map.Entry<String, String> stringStringEntry : header.entrySet()) {
					httpGet.setHeader(stringStringEntry.getKey(), stringStringEntry.getValue());
				}
			}
			//发起请求
			httpResponse = httpClient.execute(httpGet);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				Header[] tracecodes = httpResponse.getHeaders("Tracecode");
				tracecode.append(tracecodes[0].getValue());
				resultStr = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
				log.info("请求地址:{},响应结果:{}", url, resultStr);
			} else {
				StringBuffer stringBuffer = new StringBuffer();
				HeaderIterator headerIterator = httpResponse.headerIterator();
				while (headerIterator.hasNext()) {
					stringBuffer.append("\t" + headerIterator.next());
				}
				log.info("异常信息:请求地址:{},请求响应状态:{},请求返回结果:{}",url,httpResponse.getStatusLine().getStatusCode(), stringBuffer);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			HttpClientUtils.closeConnection(httpClient, httpResponse);
		}
		return resultStr;
	}


	public static String doPutRequest(String url, Map<String, String> header,StringEntity entity) {

		CloseableHttpClient closeableHttpClient = null;
		CloseableHttpResponse closeableHttpResponse=null;
		try {
			closeableHttpClient = SSLClientCustom.getHttpClinet();
		} catch (Exception e) {
			e.printStackTrace();
		}


		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectTimeout(5000)
				.setConnectionRequestTimeout(5000)
				.setRedirectsEnabled(true)
				.build();

		HttpPut httpPost = new HttpPut(url);

		httpPost.setConfig(requestConfig);
		httpPost.setHeader("Content-Type", "application/json");

		if (MapUtils.isNotEmpty(header)) {
			for (Map.Entry<String, String> stringStringEntry : header.entrySet()) {
				httpPost.setHeader(stringStringEntry.getKey(), stringStringEntry.getValue());
				log.info("请求header信息,key:{},value:{}", stringStringEntry.getKey(), stringStringEntry.getValue());
			}
		}

		String strRequest = "";
		try {
//			StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
			entity.setContentEncoding("utf-8");
			entity.setContentType("application/json");
			httpPost.setEntity(entity);


			closeableHttpResponse = closeableHttpClient.execute(httpPost);

			if (null != closeableHttpResponse && !"".equals(closeableHttpResponse)) {
				int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
				if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					HttpEntity httpEntity = closeableHttpResponse.getEntity();
					strRequest = EntityUtils.toString(httpEntity);
					log.info("请求正常,请求地址:{},响应结果:{}", url, statusCode+";"+strRequest);
				} else {
					StringBuffer stringBuffer = new StringBuffer();
					HeaderIterator headerIterator = closeableHttpResponse.headerIterator();
					while (headerIterator.hasNext()) {
						stringBuffer.append("\t" + headerIterator.next());
					}
					strRequest = "Error Response" + statusCode;
					log.info("异常信息:请求地址:{},响应状态和结果:{}",url,strRequest+";"+stringBuffer);
				}
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (closeableHttpClient != null) {
					closeableHttpClient.close();
				}

				if(closeableHttpResponse!=null){
					closeableHttpResponse.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return strRequest;
	}



	/**
	 * 关掉连接释放资源
	 */
	private static void closeConnection(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) {
		if (httpClient != null) {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (httpResponse != null) {
			try {
				httpResponse.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 构造get请求的参数
	 *
	 * @return
	 */
	private static String buildUrl(Map<String, Object> map) {
		if (MapUtils.isEmpty(map)) {
			return "";
		}
		StringBuffer stringBuffer = new StringBuffer("?");
		for (Map.Entry<String, Object> stringStringEntry : map.entrySet()) {
			stringBuffer.append(stringStringEntry.getKey()).append("=").append(stringStringEntry.getValue()).append("&");
		}
		String result = stringBuffer.toString();
		if (StringUtils.isNotEmpty(result)) {
			result = result.substring(0, result.length() - 1);//去掉结尾的&连接符
		}
		return result;
	}

}