首页 > 代码库 > httpClient工具类

httpClient工具类

package com.chinatelecom.personalcustom.common.util;

import com.chinatelecom.personalcustom.PersonalCustomConst;
import com.chinatelecom.personalcustom.model.WapLogBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.providers.netty.NettyResponse;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.jboss.netty.handler.codec.http.HttpHeaders;

import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class HttpUtil {
	/**
	 * 请求超时时间
	 */
	private static final int SO_TIMEOUT = 45000;
	/**
	 * 请求失败时重试次数
	 */
	private static final int RETRY_COUNT = 5;
	/**
	 * 最大允许连接数
	 */
	private static final int MAX_TOTAL_CONNECTION = 200;
	/**
	 * 异步请求对象
	 */
	private static AsyncHttpClient asyncHttpClient;

	private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
	
	static {
		HttpConnectionManagerParams params = new HttpConnectionManagerParams();
		params.setMaxTotalConnections(MAX_TOTAL_CONNECTION);
		connectionManager.setParams(params);
	}

	/**
	 * 设置异步请求参数
	 */
	static {
		AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder();
		builder.setMaximumConnectionsTotal(300);
		builder.setMaximumConnectionsPerHost(90);
        builder.setRequestTimeoutInMs(SO_TIMEOUT);
		asyncHttpClient = new AsyncHttpClient(builder.build());
	}

	/**
	 * 获取同步请求连接
	 */
	private static HttpClient getHttpClientInstance() {
		HttpClient client = new HttpClient(connectionManager);
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
		client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(RETRY_COUNT, true));
        client.getParams().setSoTimeout(SO_TIMEOUT);
		return client;
	}

	/**
	 * POST请求
	 */
	public static HttpResponse post(String url, Map<String,Object> params) throws Exception {
		HttpResponse response = new HttpResponse();
		HttpClient client = getHttpClientInstance();
		PostMethod postMethod = new PostMethod(url);
		postMethod.addRequestHeader(HttpHeaders.Names.USER_AGENT, PersonalCustomConst.USER_AGENT);
		postMethod.setRequestHeader(HttpHeaders.Names.CONTENT_TYPE, "UTF-8");
		ObjectMapper mapper = new ObjectMapper();
		try {
			StringRequestEntity stringRequestEntity = new StringRequestEntity(mapper.writeValueAsString(params));
			postMethod.setRequestEntity(stringRequestEntity);
			int returnCode = client.executeMethod(postMethod);
			response.setStatusCode(returnCode);
			response.setBody(postMethod.getResponseBodyAsString());
		} finally {
			postMethod.releaseConnection();
		}
		return response;
	}
	
	/**
	 * POST请求
	 */
	public static HttpResponse post(String url, String params) throws Exception {
		HttpResponse response = new HttpResponse();
		HttpClient client = getHttpClientInstance();
		PostMethod postMethod = new PostMethod(url);
		postMethod.addRequestHeader(HttpHeaders.Names.USER_AGENT, PersonalCustomConst.USER_AGENT);
		postMethod.setRequestHeader(HttpHeaders.Names.CONTENT_TYPE, "UTF-8");
		try {
			StringRequestEntity stringRequestEntity = new StringRequestEntity(params);
			postMethod.setRequestEntity(stringRequestEntity);
			int returnCode = client.executeMethod(postMethod);
			response.setStatusCode(returnCode);
			response.setBody(postMethod.getResponseBodyAsString());
		} finally {
			postMethod.releaseConnection();
		}
		return response;
	}
	
	/**
	 * GET请求
	 */
	public static HttpResponse get(String url, Map<String,String> params) throws Exception {
		HttpResponse response = new HttpResponse();
		HttpClient client = getHttpClientInstance();
		GetMethod getMethod = null;
		try {
			StringBuffer buffer = new StringBuffer();
			buffer.append(url).append("?t=").append(System.currentTimeMillis());
	        Set<Entry<String, String>> entries = params.entrySet();
	        for (Entry<String, String> entry : entries) {
	            if (entry != null && entry.getValue() != null) {
	            	buffer.append("&").append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(),"UTF-8"));
	            }
	        }
	        getMethod = new GetMethod(buffer.toString());
	        getMethod.setRequestHeader(HttpHeaders.Names.CONTENT_TYPE, "UTF-8");
	        getMethod.getParams().setContentCharset("UTF-8");  
			int returnCode = client.executeMethod(getMethod);
			response.setStatusCode(returnCode);
			response.setBody(getMethod.getResponseBodyAsString());
		} finally {
			if(getMethod != null){
				getMethod.releaseConnection();
			}
		}
		return response;
	}
	
	
	/**
	 * 异步get请求
	 */
	public static HttpResponse aysnGet(String url,Map<String, Object> params,WapLogBean wapLogBean) throws Exception {
		HttpResponse response = new HttpResponse();
		try {
			StringBuffer buffer = new StringBuffer();
			buffer.append(url);
			if(params != null && params.size() > 0){
				buffer.append("?t=").append(System.currentTimeMillis());
				Set<Entry<String, Object>> entries = params.entrySet();
		        for (Entry<String, Object> entry : entries) {
		            if (entry != null && entry.getValue() != null) {
		            	buffer.append("&").append(entry.getKey()).append("=").append(entry.getValue());
		            }
		        }
			}
			wapLogBean.setServerUrl(buffer.toString());
	        BoundRequestBuilder builder = asyncHttpClient.prepareGet(buffer.toString());
	        builder = builder.addHeader(HttpHeaders.Names.USER_AGENT,PersonalCustomConst.USER_AGENT);
	        NettyResponse nettyResponse = (NettyResponse) builder.execute().get();
			response.setStatusCode(nettyResponse.getStatusCode());
			response.setBody(nettyResponse.getResponseBody());
		} catch (Exception e) {
			throw e;
		}
		return response;
	}
	
	/**
	 * 异步post请求
	 */
	public static HttpResponse aysnPost(String url,Map<String, Object> params, String userAgent)	throws Exception {
		HttpResponse response = new HttpResponse();
		try {
	        BoundRequestBuilder builder = asyncHttpClient.preparePost(url);
	        builder = builder.addHeader(HttpHeaders.Names.USER_AGENT,userAgent);
	        if(params != null && params.size() > 0){
	            builder = builder.setBody(JsonUtil.entityToJson(params));
	        }
	        NettyResponse nettyResponse = (NettyResponse) builder.execute().get();
			response.setStatusCode(nettyResponse.getStatusCode());
			response.setBody(nettyResponse.getResponseBody());
		} catch (Exception e) {
			throw e;
		}
		return response;
	}
	
	/**
	 * 发送HTTP请求
	 */
	@SuppressWarnings("deprecation")
	public static String post(String url,String body, String userAgent, String contentType) throws Exception {
		String result = null;
		HttpClient client = getHttpClientInstance();
		PostMethod method = new PostMethod(url);
		method.addRequestHeader("User-Agent", userAgent);
		method.setRequestHeader("Content-Type", contentType);
		method.setRequestBody(body);
		try {
			client.executeMethod(method);
			result = method.getResponseBodyAsString();
		} finally {
			method.releaseConnection();
		}
		return result;
	}
	
	public static void destroy() {
        if(asyncHttpClient != null){
            asyncHttpClient.close();
        }
	}
}

httpClient工具类