1. Httpclient
1.1. 导入依赖
1.2. DoGET
1.3. 带有参数的 GET 请求
1.4. DoPOST
1.5. 带有参数的 POST 请求
public static void main(String[] args) throws Exception
{
// 创建Httpclient对象
CloseableHttpClient httpclient =
HttpClients.createDefault();
// 创建http POST请求
HttpPost httpPost = new
HttpPost("http://www.oschina.net/search");
// 伪装成浏览器
httpPost.setHeader("User-Agent", "Mozilla/5.0
(Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/50.0.2661.94 Safari/537.36");
ArrayList(0);
// 设置2个post参数,一个是scope、一个是q
List parameters = new
parameters.add(new BasicNameValuePair("scope",
parameters.add(new BasicNameValuePair("q", "java"));
"project"));
parameters.add(new BasicNameValuePair("fromerr",
"7nXH76r7"));
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new
UrlEncodedFormEntity(parameters);
// 将请求实体设置到httpPost对象中
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() ==
200) {
}
}
String content =
EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
} finally {
}
if (response != null) {
}
httpclient.close();
response.close();
1.6. 连接管理器
注意:
1.7. 定期关闭无效连接
public class ClientEvictExpiredConnections {
public static void main(String[] args) throws Exception
{
PoolingHttpClientConnectionManager cm = new
PoolingHttpClientConnectionManager();
// 设置最大连接数
cm.setMaxTotal(200);
// 设置每个主机地址的并发数
cm.setDefaultMaxPerRoute(20);
new IdleConnectionEvictor(cm).start();
}
public static class IdleConnectionEvictor extends Thread
{
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public
IdleConnectionEvictor(HttpClientConnectionManager connMgr)
{
this.connMgr = connMgr;
}
synchronized (this) {
while (!shutdown) {
wait(5000);
// 关闭失效的连接
connMgr.closeExpiredConnections();
} catch (InterruptedException ex) {
@Override
public void run() {
try {
}
}
// 结束
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
}
1.8. 设置请求参数
2. Httpclient 和 Spring 的整合