`

HttpClient

阅读更多
参考:
http://wangxinchun.iteye.com/blog/2136254
http://wangxinchun.iteye.com/blog/2156660
http://wangxinchun.iteye.com/blog/2166837


一个大的系统为了解耦,一般进行分离为多个系统,多个系统之间必然存在交互。
http协议是此种交互中最常用的,简单方便,效率也不错。

基于java语言的 apache 的开源项目HttpClient 是比较常用的工具。

我发现这个工具,很多时候大家用的并不好:
1、http连接池PoolingClientConnectionManager,项目中几乎不用。
2、DefaultHttpClient对象,每次调用都新生成,它是线程安全的,一个项目中一个即可。

下面我分享下我先前公司的使用案例:(仅供参考)
pom配置:
  <dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.2</version>
		</dependency>


java 代码:
package com.***.framework.res.api.util;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
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.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.***.framework.res.api.exception.DajieHttpRequestException;

/**
 * http请求工具类 get,post
 * 
 * @author xinchun.wang
 * 
 */
public class HttpClientUtil {
	private  static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	private  static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
	private  static final String ENCODING_GZIP = "gzip";
	private HttpClient httpclient;


	/**
	 * 通过post提交方式获取url指定的资源和数据
	 * 
	 * @param url
	 * @return
	 * @throws DajieHttpRequestException
	 */
	public  String postData(String url) throws DajieHttpRequestException {
		return postData(url, null);
	}

	/**
	 * 通过post提交方式获取url指定的资源和数据
	 * 
	 * @param url
	 * @param nameValuePairs
	 *            请求参数
	 * @return
	 * @throws DajieHttpRequestException
	 */
	public  String postData(String url, List<NameValuePair> nameValuePairs)
			throws DajieHttpRequestException {
		return postData(url, nameValuePairs, null);
	}

	/**
	 * 通过post提交方式获取url指定的资源和数据
	 * 
	 * @param url
	 * @param nameValuePairs
	 *            请求参数
	 * @param headers
	 *            请求header参数
	 * @return
	 * @throws DajieHttpRequestException
	 */
	public  String postData(String url,
			List<NameValuePair> nameValuePairs, Map<String, String> headers)
			throws DajieHttpRequestException {
		long start = System.currentTimeMillis();
		HttpPost httpPost = new HttpPost(url);
		try {
			if (headers != null && headers.size() > 0) {
				Set<Map.Entry<String, String>> set = headers.entrySet();
				for (Iterator<Map.Entry<String, String>> it = set.iterator(); it
						.hasNext();) {
					Map.Entry<String, String> header = it.next();
					if (header != null) {
						httpPost.setHeader(header.getKey(), header.getValue());
					}
				}
			}
			if (nameValuePairs != null && nameValuePairs.size() > 0) {
				httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
			}
			
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if(entity == null){
				 return null;
			}
			String info = EntityUtils.toString(entity, "UTF-8");
			return info;
		} catch (Exception e) {
			logger.debug("postData Exception url: {}", url, e);
			throw new DajieHttpRequestException(url
					+ "dajie postData exception:", e);
		} finally {
			httpPost.releaseConnection();
			long interval = System.currentTimeMillis() - start;
			logger.debug("{} 请求耗时:{} ", url, interval);
		}
	}
	
	/**
	 * 通过ContentType 为json的格式进行http传输
	 * @param url 远程url
	 * @param content 传输内容
	 * @return
	 * @throws DajieHttpRequestException
	 */
	public  String postJSONData(String url, String content) throws DajieHttpRequestException {
		long start = System.currentTimeMillis();
		HttpPost httpPost = new HttpPost(url);
		try {
			if (content != null && content.length() > 0) {
				httpPost.setEntity(new StringEntity(content,ContentType.APPLICATION_JSON));
			}
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if(entity == null){
				 return null;
			}
			String info = EntityUtils.toString(entity, "UTF-8");
			return info;
		} catch (Exception e) {
			logger.debug("postData Exception url: {}", url, e);
			throw new DajieHttpRequestException(url
					+ "dajie postDataByJson exception:", e);
		} finally {
			httpPost.releaseConnection();
			long interval = System.currentTimeMillis() - start;
			logger.debug("{} 请求耗时:{} ", url, interval);
		}
	}

	/**
	 * 通过get方法获取url资源的数据
	 * 
	 * @param url
	 *            服务器地址
	 * @return 返回响应的文本,如果请求发生异常,抛出DajieHttpRequestException
	 * @throws DajieHttpRequestException
	 */
	public  String getData(String url) throws DajieHttpRequestException {
		return getData(url, null);
	}

	/**
	 * 带header的get请求
	 * 
	 * @param url
	 *            服务器地址
	 * @param headers
	 *            添加的请求header信息
	 * @return 返回服务器响应的文本,出错抛出DajieHttpRequestException异常
	 * @throws DajieHttpRequestException
	 */
	public  String getData(String url, Map<String, String> headers)
			throws DajieHttpRequestException {
		long start = System.currentTimeMillis();
		HttpGet httpGet = new HttpGet(url);
		if (headers != null && headers.size() > 0) {
			Set<Map.Entry<String, String>> set = headers.entrySet();
			for (Iterator<Map.Entry<String, String>> it = set.iterator(); it
					.hasNext();) {
				Map.Entry<String, String> header = it.next();
				if (header != null) {
					httpGet.setHeader(header.getKey(), header.getValue());
				}
			}
		}
		try {
			HttpResponse response =  httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if(entity == null){
				 return null;
			}
			String info = EntityUtils.toString(entity, "UTF-8");
			return info;
		} catch (Exception e) {
			logger.debug("getData Exception url: {}", url, e);
			throw new DajieHttpRequestException(url
					+ "dajie getData exception:", e);
		} finally {
			httpGet.releaseConnection();
			long interval = System.currentTimeMillis() - start;
			logger.debug("{} 请求耗时:{} ", url, interval);
		}
	}

	/**
	 * 对httpclient 做压缩处理和解压缩处理
	 * 
	 * @param httpclient
	 */
	public void initClient() {
		((DefaultHttpClient)httpclient).addRequestInterceptor(new HttpRequestInterceptor() {
			@Override
			public void process(HttpRequest request, HttpContext context) {
				if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
					request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
				}
			}
		});

		((DefaultHttpClient)httpclient).addResponseInterceptor(new HttpResponseInterceptor() {
			@Override
			public void process(HttpResponse response, HttpContext context) {
				final HttpEntity entity = response.getEntity();
				if(entity == null){
					return;
				}
				final Header encoding = entity.getContentEncoding();
				if (encoding != null) {
					for (HeaderElement element : encoding.getElements()) {
						if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
							response.setEntity(new GzipDecompressingEntity(
									response.getEntity()));
							break;
						}
					}
				}
			}
		});
	}

	/**
	 * 关闭客户端
	 */
	public void destroyClient(){
		httpclient.getConnectionManager().shutdown();
	}
	/**
	 * post方式处理文件和图片上传
	 * 
	 * @param url
	 *            服务器地址
	 * @param data
	 *            byte数组数据
	 * @param fileName
	 *            文件名
	 * @return 返回服务器响应信息,否则抛出DajieHttpRequestException异常
	 * @throws DajieHttpRequestException
	 */
	public  String postMultipartData(String url, byte[] data,
			String fileName) throws DajieHttpRequestException {
		long start = System.currentTimeMillis();
		HttpPost httpPost = new HttpPost(url);
		try {
			if (data != null && data.length > 0) {
				MultipartEntity reqEntity = new MultipartEntity();
				ContentBody contentBody = new ByteArrayBody(data, fileName);
				reqEntity.addPart("file", contentBody);
				httpPost.setEntity(reqEntity);
			}
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			String info = EntityUtils.toString(entity, "UTF-8");
			return info;
		} catch (Exception e) {
			logger.debug("postMultipartData Exception url: {}", url, e);
			throw new DajieHttpRequestException(url
					+ "dajie postMultipartData exception:", e);
		} finally {
			httpPost.releaseConnection();
			long interval = System.currentTimeMillis() - start;
			logger.debug("{} 请求耗时:{} ", url, interval);
		}
	}

	/**
	 * put 方式提交数据
	 * 
	 * @param url
	 *            :服务器地址
	 * @param nameValuePairs
	 *            :参数
	 * @return 返回 服务器返回的文本信息,报错会抛出异常
	 * @throws DajieHttpRequestException
	 */
	public  String putData(String url, List<NameValuePair> nameValuePairs)
			throws DajieHttpRequestException {
		long start = System.currentTimeMillis();
		HttpPut httpPut = new HttpPut(url);

		try {
			if (nameValuePairs != null && nameValuePairs.size() > 0) {
				httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairs,
						"UTF-8"));
			}
			HttpResponse response = httpclient.execute(httpPut);
			HttpEntity entity = response.getEntity();
			if(entity == null){
				 return null;
			}
			String info = EntityUtils.toString(entity, "UTF-8");
			return info;
		} catch (Exception e) {
			logger.debug("putData Exception url:{}", url, e);
			throw new DajieHttpRequestException(url
					+ "dajie putData exception:", e);
		} finally {
			httpPut.releaseConnection();
			long interval = System.currentTimeMillis() - start;
			logger.debug("{} 请求耗时:{} ", url, interval);
		}
	}

	/**
	 * delete 方式提交数据
	 * 
	 * @param url
	 *            服务器地址
	 * @return 返回 服务器返回的文本信息,报错会抛出异常
	 * @throws DajieHttpRequestException
	 */
	public  String deleteData(String url)
			throws DajieHttpRequestException {
		return deleteData(url, null);
	}

	/**
	 * delete 方式提交数据
	 * 
	 * @param url
	 *            服务器地址
	 * @return 返回 服务器返回的文本信息,报错会抛出异常
	 */
	public  String deleteData(String url, Map<String, String> headers)
			throws DajieHttpRequestException {
		long start = System.currentTimeMillis();
		HttpDelete httpDelete = new HttpDelete(url);

		if (headers != null && headers.size() > 0) {
			Set<Map.Entry<String, String>> set = headers.entrySet();
			for (Iterator<Map.Entry<String, String>> it = set.iterator(); it
					.hasNext();) {
				Map.Entry<String, String> header = it.next();
				if (header != null) {
					httpDelete.setHeader(header.getKey(), header.getValue());
				}
			}
		}
		try {
			HttpResponse response = httpclient.execute(httpDelete);
			HttpEntity entity = response.getEntity();
			String info = EntityUtils.toString(entity, "UTF-8");
			return info;
		} catch (Exception e) {
			logger.debug("putData Exception url {} ", url, e);
			throw new DajieHttpRequestException(url
					+ "dajie deleteDate exception:", e);
		} finally {
			httpDelete.releaseConnection();
			long interval = System.currentTimeMillis() - start;
			logger.debug("{} 请求耗时:{} ", url, interval);
		}
	}
	
	/**
	 * 下载媒体资源
	 * @param url
	 * @return
	 * @throws DajieHttpRequestException
	 */
	public byte[] getMultipartData(String url) throws DajieHttpRequestException{
		long start = System.currentTimeMillis();
		HttpGet httpGet = new HttpGet(url);
		try {
			HttpResponse response =  httpclient.execute(httpGet);
			byte[] result = EntityUtils.toByteArray(response.getEntity());
			return result;
		}catch(Exception e){
			logger.debug("putData Exception url {} ", url, e);
			throw new DajieHttpRequestException(url+ "dajie getMultipartData exception:", e);
		}finally{
			httpGet.releaseConnection();
			long interval = System.currentTimeMillis() - start;
			logger.debug("{} 请求耗时:{} ", url, interval);
		}
	}

	public void setHttpclient(HttpClient httpclient) {
		this.httpclient = httpclient;
	}
}



spring 配置:
<bean id="connManager" class="org.apache.http.impl.conn.PoolingClientConnectionManager">
	   <property name="maxTotal" value="#{internalConfiguration.maxTotal}"/>
	   <property name="defaultMaxPerRoute" value="#{internalConfiguration.defaultMaxPerRoute}"/>
	</bean>
	
	<bean id="httpclient" class="org.apache.http.impl.client.DefaultHttpClient">
	   <constructor-arg>
	      <ref bean="connManager"/>
	   </constructor-arg>
	</bean>
	
	<bean id="httpClientUtil" class="com.***.framework.res.api.util.HttpClientUtil" init-method="initClient" destroy-method="destroyClient">
	   <property name="httpclient" ref="httpclient"/>
	</bean> 


注意:这个配置很重要,尤其 是参数:maxTotal 和 defaultMaxPerRoute 。
defaultMaxPerRoute :对一个路由(url)地址,最多同时存在几个连接。
0
0
分享到:
评论

相关推荐

    httpClient

    HttpClient httpClient = new HttpClient(); // 设置 Http 连接超时为5秒 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); /* 2 生成 GetMethod 对象并设置参数 */ GetMethod ...

    httpclient-4.5.6-API文档-中文版.zip

    赠送jar包:httpclient-4.5.6.jar; 赠送原API文档:httpclient-4.5.6-javadoc.jar; 赠送源代码:httpclient-4.5.6-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.6.pom; 包含翻译后的API文档:httpclient...

    httpclient

    使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。 1. 创建HttpClient对象。 2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建...

    httpclient-4.5.13-API文档-中英对照版.zip

    赠送jar包:httpclient-4.5.13.jar; 赠送原API文档:httpclient-4.5.13-javadoc.jar; 赠送源代码:httpclient-4.5.13-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.13.pom; 包含翻译后的API文档:...

    httpclient-4.5.5-API文档-中文版.zip

    赠送jar包:httpclient-4.5.5.jar; 赠送原API文档:httpclient-4.5.5-javadoc.jar; 赠送源代码:httpclient-4.5.5-sources.jar; 包含翻译后的API文档:httpclient-4.5.5-javadoc-API文档-中文(简体)版.zip ...

    httpclient-4.5.13-API文档-中文版.zip

    赠送jar包:httpclient-4.5.13.jar; 赠送原API文档:httpclient-4.5.13-javadoc.jar; 赠送源代码:httpclient-4.5.13-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.13.pom; 包含翻译后的API文档:...

    可用org.apache.commons.httpclient-3.1.0.jar.zip

    import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods....

    httpclient-4.5jar

    httpclient-4.5所需jar包,里面包含httpclient-4.5.jar等等10个必须的开发包。 1.commons-codec-1.9.jar 2.commons-logging-1.2.jar 3.fluent-hc-4.5.jar 4.httpclient-4.5.jar 5.httpclient-cache-4.5.jar 6....

    httpclient4.5.3 jar完整包含所有依赖包

    HttpClient 4.5.3 (GA) is a maintenance release that fixes a number of defects found since 4.5.2. Please note that as of 4.4 HttpClient requires Java 1.6 or newer. Changelog: ------------------- * ...

    httpclient.jar包下载

    httpclient.jar下载 包括code.jar包

    SpringBoot使用httpclient发送Post请求时

    try(CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(url); StringEntity stringEntity = new StringEntity(params, Charset.forName("UTF-8")); ...

    Android_HttpClient_jar包

    Android使用HttpClient发送请求、接收响应很简单,只要如下几步即可: Step1:创建HttpClient对象; Step2:如果需要发送GET请求,则创建HttpGet对象; 如果需要发送POST请求,则创建HttpPost对象; Step3:如果...

    httpclient-4.2.5-API文档-中文版.zip

    赠送jar包:httpclient-4.2.5.jar; 赠送原API文档:httpclient-4.2.5-javadoc.jar; 赠送源代码:httpclient-4.2.5-sources.jar; 赠送Maven依赖信息文件:httpclient-4.2.5.pom; 包含翻译后的API文档:httpclient...

    httpclient-4.5.10-API文档-中文版.zip

    赠送jar包:httpclient-4.5.10.jar; 赠送原API文档:httpclient-4.5.10-javadoc.jar; 赠送源代码:httpclient-4.5.10-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.10.pom; 包含翻译后的API文档:...

    HttpClient以及获取页面内容应用

    压缩包中含有多个文档,从了解httpclient到应用。 httpClient 1httpClint 1.1简介 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持...

    httpclient-4.5.2-API文档-中文版.zip

    赠送jar包:httpclient-4.5.2.jar; 赠送原API文档:httpclient-4.5.2-javadoc.jar; 赠送源代码:httpclient-4.5.2-sources.jar; 包含翻译后的API文档:httpclient-4.5.2-javadoc-API文档-中文(简体)版.zip ...

    httpclient-4.4-API文档-中文版.zip

    赠送jar包:httpclient-4.4.jar; 赠送原API文档:httpclient-4.4-javadoc.jar; 赠送源代码:httpclient-4.4-sources.jar; 赠送Maven依赖信息文件:httpclient-4.4.pom; 包含翻译后的API文档:httpclient-4.4-...

    HttpClient 3.x to HttpComponents HttpClient 4.x

    帮助程序员快速从Apache的HttpClient 3.x升级到HttpClient 4.x

    httpclient-4.5.3-API文档-中文版.zip

    赠送jar包:httpclient-4.5.3.jar 赠送原API文档:httpclient-4.5.3-javadoc.jar 赠送源代码:httpclient-4.5.3-sources.jar 包含翻译后的API文档:httpclient-4.5.3-javadoc-API文档-中文(简体)版.zip 对应Maven...

Global site tag (gtag.js) - Google Analytics