实践CommonsHttpClient

Commons HttpClient

addRequestHeader(key,value)

body

setRequestEntity(RequestEntity)

RequestEntity是对body的一种包装。

RequestEntity

setRequestBody(String)

setRequestBody(InputStream)

setParameter(name,value):通过PostMethod#generateRequestEntity-》EncodingUtil#formUrlEncode转换为RequestEntity,字符串表示形式为name1=value1&name2=value2

HTTP protocol parameters

1
2
3
// 下面两种方法等价
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
postMethod.getParams().setContentCharset("utf-8");

connection manager

关闭相应的io对象即可,会自动回收连接到连接池。

HttpConnectionManager

HttpConnectionManager有三个自带实现SimpleHttpConnectionManagerMultiThreadedHttpConnectionManager

1
2
3
4
MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager();
		multiThreadedHttpConnectionManager.getParams().setDefaultMaxConnectionsPerHost(maxHostConnections);
		multiThreadedHttpConnectionManager.getParams().setMaxTotalConnections(maxTotalConnections);
		client = new HttpClient(multiThreadedHttpConnectionManager);