HttpClientUtil-工具类

                                HttpClientUtil-工具类

代码

package cn.hlbdx;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

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.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;


public class HttpClientUtil {

	/**
	 * Get请求
	 * 
	 * @param url
	 * @return
	 */
	public static String doGet(String url) {
		// 创建Httpclient对象
		PoolingHttpClientConnectionManager httpClientConnectionManager = getHttpClientConnectionManager();
		CloseableHttpClient httpclient = HttpClients.custom()
				.setConnectionManager(httpClientConnectionManager).build();
		// 创建http GET请求
		HttpGet httpGet = new HttpGet(url);
		RequestConfig config = getRequestConfig();
		// 设置请求配置信息
		httpGet.setConfig(config);
		CloseableHttpResponse response = null;
		// 执行请求
		try {
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(response.getEntity(),
						"UTF-8");
				return result;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * get的请求
	 * 
	 * @param url
	 * @param param
	 * @return
	 */
	public static String doGet(String url, Map<String, String> param) {
		PoolingHttpClientConnectionManager httpClientConnectionManager = getHttpClientConnectionManager();
		CloseableHttpClient httpclient = HttpClients.custom()
				.setConnectionManager(httpClientConnectionManager).build();
		URI uri = null;
		try {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			if (param != null && !param.isEmpty()) {
				Set<String> keySet = param.keySet();
				Iterator<String> iterator = keySet.iterator();
				while (iterator.hasNext()) {
					NameValuePair nameValuePair = new BasicNameValuePair(
							iterator.next(), param.get(keySet));
					nvps.add(nameValuePair);
				}
			}
			uri = new URIBuilder(url).setParameters(nvps).build();
		} catch (URISyntaxException e) {
			e.printStackTrace();
			return null;
		}
		HttpGet httpGet = new HttpGet(uri);
		RequestConfig config = getRequestConfig();
		// 设置请求配置信息
		httpGet.setConfig(config);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(response.getEntity(),
						"UTF-8");
				return result;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * POST请求
	 * 
	 * @param url
	 * @return
	 */
	public static String doPost(String url) {
		PoolingHttpClientConnectionManager httpClientConnectionManager = getHttpClientConnectionManager();
		CloseableHttpClient httpclient = HttpClients.custom()
				.setConnectionManager(httpClientConnectionManager).build();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig config = getRequestConfig();
		// 设置请求配置信息
		httpPost.setConfig(config);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(response.getEntity(),
						"UTF-8");
				return result;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return null;
	}

	/**
	 * Post请求
	 * 
	 * @param url
	 * @param param
	 * @return
	 */
	public static String doPost(String url, Map<String, String> param) {
		PoolingHttpClientConnectionManager httpClientConnectionManager = getHttpClientConnectionManager();
		CloseableHttpClient httpclient = HttpClients.custom()
				.setConnectionManager(httpClientConnectionManager).build();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig config = getRequestConfig();
		// 设置请求配置信息
		httpPost.setConfig(config);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>(0);
		if (param != null && !param.isEmpty()) {
			Set<String> keySet = param.keySet();
			Iterator<String> iterator = keySet.iterator();
			while (iterator.hasNext()) {
				NameValuePair nameValuePair = new BasicNameValuePair(
						iterator.next(), param.get(keySet));
				nvps.add(nameValuePair);
			}
		}
		UrlEncodedFormEntity formEntity;
		try {
			formEntity = new UrlEncodedFormEntity(nvps);
			httpPost.setEntity(formEntity);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(response.getEntity(),
						"UTF-8");
				return result;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * HttpClient连接管理者
	 * 
	 * @return
	 */
	public static PoolingHttpClientConnectionManager getHttpClientConnectionManager() {
		PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
		// 设置最大连接数
		httpClientConnectionManager.setMaxTotal(200);
		// 设置每个主机地址的并发数
		httpClientConnectionManager.setDefaultMaxPerRoute(20);
		// ...
		return httpClientConnectionManager;
	}

	/**
	 * 获取请求配置信息
	 * 
	 * @return
	 */
	public static RequestConfig getRequestConfig() {
		// 构建请求配置信息
		RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 创建连接的最长时间
				.setConnectionRequestTimeout(500) // 从连接池中获取到连接的最长时间
				.setSocketTimeout(10 * 1000) // 数据传输的最长时间
				.setStaleConnectionCheckEnabled(true) // 提交请求前测试连接是否可用
				.build();
		return config;
	}
}

pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>cn.hlbdx</groupId>
	<artifactId>Demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<dependencies>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3.5</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.7</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
			<version>1.3.2</version>
		</dependency>
	</dependencies>
</project>

log4j.properties

log4j.rootLogger=DEBUG,A1
log4j.logger.org.mybatis = DEBUG

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值