欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpClient

程序员文章站 2024-02-01 10:44:04
...

HttpClient是一个模拟HTTP请求的工具类,目前我们在两个地方用到了HttpClient。

  1. Eclipse插件调用第三方的HTTP接口。
  2. Action自动化测试。

我们对HttpClient进行了一个简单的封装:

 

package com.alibaba.itu.tala.util;

import static org.apache.commons.httpclient.params.HttpMethodParams.SO_TIMEOUT;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 * HTTP 工具类.
 * 
 * @author tengfei.fangtf
 * 
 */
public class HttpUtil {

	/**
	 * 默认编码为 GB2312
	 */
	private static final String HTTP_CONTENT_CHARSET = "gb2312";

	private static TalaLogger log = TalaLogger.getLogger();

	public static final Integer MAX_TIME_OUT = 5000;
	public static final Integer MAX_IDLE_TIME_OUT = 60000;
	public static final Integer MAX_CONN = 100;

	public static HttpClient httpClient = null;

	static {
		MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
		connectionManager.closeIdleConnections(MAX_IDLE_TIME_OUT);
		connectionManager.getParams().setParameter(
				"http.connection-manager.max-total", MAX_CONN);
		httpClient = new HttpClient(connectionManager);
		httpClient.getParams().setParameter(SO_TIMEOUT,
				MAX_TIME_OUT);
		httpClient.getParams().setParameter("http.connection.timeout",
				MAX_TIME_OUT);
		httpClient.getParams().setParameter("http.connection-manager.timeout",
				MAX_TIME_OUT.longValue());
	}

	/**
	 * 发送HTTP请求
	 * 
	 * @param url
	 * @param param
	 * @return HTTP响应
	 */
	public static String sendSimplePostRequest(String url,
			Map<String, Object> param) {
		// HTTP方法,还有get,head,put,delete,connect,options(询问可用的选项)
		PostMethod post = new PostMethod(url);
		post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
				HTTP_CONTENT_CHARSET);
		if (param != null) {
			for (Entry<String, Object> entry : param.entrySet()) {
				// 排除掉空值
				if (entry.getValue() != null) {
					post.addParameter(entry.getKey(), entry.getValue()
							.toString());
				}
			}
		}
		try {
			post.addRequestHeader(new Header("Connection", "close"));
			// post.addRequestHeader("Cookie", "ID=1"); //添加Cookie
			httpClient.executeMethod(post);
			if (post.getStatusCode() == HttpStatus.SC_OK) {
				return post.getResponseBodyAsString();
			} else {
				post.abort();//马上断开连接
				log.error("Http Comunication error ! code --> "
						+ post.getStatusCode(), null);
			}
		} catch (Exception e) {
			log
					.error("Http post occur error!url=" + url + ",param="
							+ param, e);
		} finally {
			post.releaseConnection();
		}
		return null;
	}

}
 

依赖jakarta.commons.httpclient-3.1.jar

 

 

相关标签: http java