Http请求工具类(Get请求和Post请求)

1、首先加入依赖

		<!-- http请求 -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>

		<!-- 日志 -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>

2、工具类HttpClientUtil

package com.dong.pay.util;

import java.net.URL;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
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.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * Http请求工具类
 * 
 * @author caishaodong
 *
 */
public class HttpClientUtil {

	private static final Logger LOGGER = Logger.getLogger(HttpClientUtil.class);

	private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000)
			.setConnectionRequestTimeout(15000).build();
	private boolean checkTimeout = true;

	public HttpClientUtil() {

	}

	/**
	 * 发送 get请求
	 * 
	 * @param httpUrl
	 */
	public String sendHttpGet(String httpUrl) {
		LOGGER.info("请求sendHttpGet方法,参数httpUrl=" + httpUrl);
		HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
		return httpGet(httpGet);
	}

	/**
	 * 发送 get请求Https
	 * 
	 * @param httpUrl
	 */
	public String sendHttpsGet(String httpUrl) {
		LOGGER.info("请求sendHttpsGet方法,参数httpUrl=" + httpUrl);
		HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
		return httpsGet(httpGet);
	}

	/**
	 * 发送Get请求
	 * 
	 * @param httpPost
	 * @return
	 */
	private String httpGet(HttpGet httpGet) {
		LOGGER.info("请求httpGet方法");
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String responseContent = null;
		try {
			// 创建默认的httpClient实例.
			httpClient = HttpClients.createDefault();
			if (this.checkTimeout)
				httpGet.setConfig(requestConfig);
			// 执行请求
			response = httpClient.execute(httpGet);
			entity = response.getEntity();
			responseContent = EntityUtils.toString(entity, "UTF-8");
			LOGGER.info("请求httpGet方法响应信息:responseContent=" + responseContent);
		} catch (Exception e) {
			LOGGER.error("请求httpGet方法异常,异常信息:" + e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				// 关闭连接,释放资源
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (Exception e) {
				LOGGER.error("请求httpGet方法,关闭连接异常,异常信息:" + e.getMessage());
				e.printStackTrace();
			}
		}
		return responseContent;
	}

	/**
	 * 发送Get请求Https
	 * 
	 * @param httpPost
	 * @return
	 */
	private String httpsGet(HttpGet httpGet) {
		LOGGER.info("请求httpsGet方法");
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String responseContent = null;
		try {
			// 创建默认的httpClient实例.
			PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader
					.load(new URL(httpGet.getURI().toString()));
			DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
			httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
			if (this.checkTimeout)
				httpGet.setConfig(requestConfig);
			// 执行请求
			response = httpClient.execute(httpGet);
			entity = response.getEntity();
			responseContent = EntityUtils.toString(entity, "UTF-8");
			LOGGER.info("请求httpsGet方法响应信息:responseContent=" + responseContent);
		} catch (Exception e) {
			LOGGER.error("请求httpsGet方法异常,异常信息:" + e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				// 关闭连接,释放资源
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (Exception e) {
				LOGGER.error("请求httpsGet方法,关闭连接异常,异常信息:" + e.getMessage());
				e.printStackTrace();
			}
		}
		return responseContent;
	}

	/**
	 * 发送 post请求
	 * 
	 * @param httpUrl
	 *            地址
	 */
	public String sendHttpPost(String httpUrl) {
		LOGGER.info("请求sendHttpPost方法,请求参数httpUrl=" + httpUrl);
		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
		return httpPost(httpPost);
	}

	/**
	 * 发送 post请求
	 * 
	 * @param httpUrl
	 *            地址
	 * @param params
	 *            参数(格式:key1=value1&key2=value2)
	 */
	public String sendHttpPost(String httpUrl, String params) {
		LOGGER.info("请求sendHttpPost方法,请求参数httpUrl=" + httpUrl + ",params=" + params);
		String responseContent = null;
		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
		try {
			// 设置参数
			StringEntity stringEntity = new StringEntity(params, "UTF-8");
			stringEntity.setContentType("application/x-www-form-urlencoded");
			httpPost.setEntity(stringEntity);
			responseContent = httpPost(httpPost);
		} catch (Exception e) {
			LOGGER.error("请求sendHttpPost方法异常,异常信息:" + e.getMessage());
			e.printStackTrace();
		}
		return responseContent;
	}

	/**
	 * 发送 post请求
	 * 
	 * @param httpUrl
	 *            地址
	 * @param maps
	 *            参数
	 */
	public String sendHttpPost(String httpUrl, Map<String, String> maps) {
		LOGGER.info("请求sendHttpPost方法,请求参数httpUrl=" + httpUrl + ",maps=" + maps);
		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
		// 创建参数队列
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		for (String key : maps.keySet()) {
			nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
		} catch (Exception e) {
			LOGGER.error("请求sendHttpPost方法异常,异常信息:" + e.getMessage());
			e.printStackTrace();
		}
		return httpPost(httpPost);
	}

	/**
	 * 发送Post请求
	 * 
	 * @param httpPost
	 * @return
	 */
	private String httpPost(HttpPost httpPost) {
		LOGGER.info("请求httpPost方法");
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String responseContent = null;
		try {
			// 创建默认的httpClient实例.
			httpClient = HttpClients.createDefault();
			if (this.checkTimeout)
				httpPost.setConfig(requestConfig);
			// 执行请求
			response = httpClient.execute(httpPost);
			entity = response.getEntity();
			responseContent = EntityUtils.toString(entity, "UTF-8");
			LOGGER.info("请求httpPost方法响应信息:responseContent=" + responseContent);
		} catch (Exception e) {
			LOGGER.error("请求httpPost方法异常,异常信息:" + e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				// 关闭连接,释放资源
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (Exception e) {
				LOGGER.error("请求httpPost方法,关闭连接异常,异常信息:" + e.getMessage());
				e.printStackTrace();
			}
		}
		return responseContent;
	}

	public String sendHttpsPost(String httpUrl, Map<String, String> maps) {
		LOGGER.info("请求sendHttpsPost方法,参数httpUrl=" + httpUrl + ",maps=" + maps);
		String responseContent = null;
		HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
		// 创建参数队列
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		if (null != maps) {
			for (String key : maps.keySet()) {
				nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
			}
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
			responseContent = httpsPost(httpPost);
		} catch (Exception e) {
			LOGGER.error("请求sendHttpPost方法异常,异常信息:" + e.getMessage());
			e.printStackTrace();
		}
		return responseContent;
	}

	private String httpsPost(HttpPost httpPost) throws Exception {
		LOGGER.info("请求httpsPost方法");
		// 采用绕过验证的方式处理https请求
		SSLContext sslcontext = createIgnoreVerifySSL();
		// 设置协议http和https对应的处理socket链接工厂的对象
		Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("http", PlainConnectionSocketFactory.INSTANCE)
				.register("https", new SSLConnectionSocketFactory(sslcontext)).build();
		PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
		HttpClients.custom().setConnectionManager(connManager);
		// 创建自定义的httpclient对象
		CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
		// 执行请求操作,并拿到结果(同步阻塞)
		CloseableHttpResponse response = client.execute(httpPost);
		// 获取结果实体
		HttpEntity entity = response.getEntity();
		String body = "";
		if (entity != null) {
			// 按指定编码转换结果实体为String类型
			body = EntityUtils.toString(entity, "UTF-8");
		}
		LOGGER.info("请求httpsPost方法响应信息:body=" + body);
		EntityUtils.consume(entity);
		// 释放链接
		response.close();
		return body;
	}

	/**
	 * 绕过验证
	 * 
	 * @return
	 * @throws Exception
	 */
	private SSLContext createIgnoreVerifySSL() throws Exception {
		SSLContext sc = SSLContext.getInstance("SSL");
		// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
		X509TrustManager trustManager = new X509TrustManager() {
			@Override
			public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
					String paramString) throws CertificateException {
			}

			@Override
			public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
					String paramString) throws CertificateException {
			}

			@Override
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		sc.init(null, new TrustManager[] { trustManager }, null);
		return sc;
	}

	/**
	 * 是否校验超时时间
	 * 
	 * @return true:校验<br>
	 *         false:不校验(默认)
	 */
	public boolean isCheckTimeout() {
		return checkTimeout;
	}

	/**
	 * 设置是否校验超时时间
	 * 
	 * @param checkTimeout
	 *            true:校验<br>
	 *            false:不校验(默认)
	 */
	public void setCheckTimeout(boolean checkTimeout) {
		this.checkTimeout = checkTimeout;
	}

}

猜你喜欢

转载自blog.csdn.net/qq_39101581/article/details/81664971