`

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.jar包下载

    《深入解析httpclient.jar及其与code.jar的关联》 在Java开发中,HTTP通信是不可或缺的一部分,而Apache HttpClient库正是Java实现HTTP客户端操作的重要工具。本文将深入探讨httpclient.jar包,以及它与code.jar包...

    HttpClient4.2.1版本的Jar包

    HttpClient 4.2.1版本引入了一些重要的改进和修复,以提高性能和稳定性。以下是一些关键特性: 1. **连接管理**:HttpClient 4.2.1引入了更完善的连接管理机制,允许开发者控制连接的创建、复用和关闭。`...

    HttpClient 3.x to HttpComponents HttpClient 4.x

    例如,在HttpClient 3.x中,代码可能会使用`***mons.httpclient.HttpClient`类和`***mons.httpclient.methods.GetMethod`等,而在4.x版本中,这些都被新的API所替代。程序员需要熟悉`org.apache....

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

    httpclient4.2.1.zip

    本文将深入探讨HttpClient 4.2.1的核心特性和使用方法,帮助开发者更好地理解和应用这个强大的工具。 一、HttpClient简介 HttpClient是一个开放源码的Java库,由Apache软件基金会维护。它为Java程序员提供了一个...

    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请求,创建...

    HttpClientHelper 工具类

    HttpClientHelper 对这个类进行了封装,使得开发者无需直接与HttpClient接口打交道,而是通过更简洁、易用的方法调用来实现网络通信。这提高了代码的可读性和可维护性。 单例模式是软件设计模式的一种,确保一个类...

    HttpClient所需jar包(全) httpClient.4.13jar

    HttpClient 4.13版本是这个库的一个较新版本,包含了一系列的改进和修复。 在Java开发中,HttpClient是一个常用的工具,尤其在处理Web服务或者API调用时。它支持同步和异步操作,可以处理复杂的HTTP协议细节,使...

    httpClient实例httpClient调用 http/https实例 忽略SSL验证

    这个实例主要涉及如何配置HttpClient来忽略SSL(Secure Socket Layer)验证,这对于在开发和测试环境中处理自签名证书或未认证的服务器非常有用。以下将详细介绍HttpClient的使用以及如何进行SSL验证的忽略。 首先...

    httpclient方式调用url

    本篇文章将深入探讨如何使用HttpClient方式调用URL,以及相关的知识点。 首先,HttpClient允许我们构建复杂的HTTP请求,包括GET、POST以及其他HTTP方法。使用HttpClient调用URL的基本步骤包括创建HttpClient实例、...

    httpClient需要的jar包

    本压缩包文件"httpClient"很可能包含了HttpClient库所需的必备JAR文件,这些文件通常包括HttpClient的核心库、依赖的第三方库以及可能的扩展模块。为了正确使用HttpClient,你需要确保将这些JAR文件添加到你的项目类...

    HttpClient 调用WebService示例

    在本文中,我们将深入探讨如何使用HttpClient调用WebService。 首先,调用WebService通常涉及SOAP(Simple Object Access Protocol)或RESTful API。HttpClient可以处理这两种类型的Web服务。在本示例中,我们假设...

    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文档:...

    HTTPClient

    ### HTTPClient知识点详解 #### 1. HttpClient4 – 获取状态码 **1.1 概览** 本节将详细介绍如何使用HttpClient 4.x版本来获取HTTP响应的状态码,并对其进行验证。这对于开发人员来说是一个非常实用的功能,可以...

    httpClient组合包.zip

    此外,HttpClient还支持异步操作,可以在多线程环境中高效地处理并发请求。 2. **httpcore-4.4.12.jar**:这是HttpClient的核心库,包含了HTTP协议的基本组件,如连接管理、请求和响应模型、编码器和解码器等。...

    Java HttpClient 全部的jar包

    在Java项目中,使用HttpClient可以实现与Web服务器的高效通信。下面将详细介绍这12个jar包的作用及其在HttpClient中的功能: 1. `commons-beanutils-1.8.0.jar`: Apache Commons BeanUtils库提供了对Java Beans属性...

    Arduino HttpClient 库文件

    1. **实例化 HttpClient 对象**:首先,你需要创建一个 `HttpClient` 类的实例,例如 `HttpClient client;` 2. **设置服务器信息**:调用 `client.begin()` 函数,传入你要访问的服务器地址和端口号,如 `client....

Global site tag (gtag.js) - Google Analytics