相对于httpurlconnection ,httpclient更加丰富,也更加强大,其中apache有两个项目都是httpclient,一个是commonts包下的,这个是通用的,更专业的是org.apache.http.包下的,所以我一般用后者;
httpclient可以处理长连接,保存会话,重连接,以及请求过滤器,连接重用等等...
下面是测试代码(全部总结来自官方文档,以及翻译)
须要下载核心包:httpclient-4.3.4.jar ,也可在官网下载:http://hc.apache.org/downloads.cgi
-
-
-
-
-
-
-
-
-
-
-
-
-
private static void test9() throws InterruptedException,ExecutionException, IOException {
-
-
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
-
connManager.setMaxTotal(200);
-
connManager.setDefaultMaxPerRoute(3);
-
HttpHost host = new HttpHost("webservice.webxml.com.cn");
-
connManager.setMaxPerRoute(new HttpRoute(host), 5);
-
-
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
-
-
String[] urisToGet = {
-
"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",
-
"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",
-
"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",
-
"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",
-
"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",
-
"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",
-
"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",
-
"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",
-
"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo",
-
"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getDatabaseInfo" };
-
-
GetThread[] threads = new GetThread[urisToGet.length];
-
-
for (int i = 0; i < threads.length; i++) {
-
HttpGet httpget = new HttpGet(urisToGet[i]);
-
threads[i] = new GetThread(httpClient, httpget);
-
}
-
-
for (int j = 0; j < threads.length; j++) {
-
threads[j].start();
-
}
-
-
for (int j = 0; j < threads.length; j++) {
-
threads[j].join();
-
}
-
-
-
}
-
-
static class GetThread extends Thread {
-
private final CloseableHttpClient httpClient;
-
private final HttpContext context;
-
private final HttpGet httpget;
-
-
public GetThread(CloseableHttpClient httpClient, HttpGet httpget) {
-
this.httpClient = httpClient;
-
this.context = HttpClientContext.create();
-
this.httpget = httpget;
-
}
-
-
@Override
-
public void run() {
-
try {
-
CloseableHttpResponse response = httpClient.execute(httpget, context);
-
try {
-
HttpEntity entity = response.getEntity();
-
if(entity!=null){
-
System.out.println("test");
-
}
-
} finally {
-
response.close();
-
}
-
} catch (ClientProtocolException ex) {
-
} catch (IOException ex) {
-
}
-
}
-
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
private static void test10(){
-
-
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/u014704496/article/details/40863045
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
-
发表于 2020-03-07 23:23:01
- 阅读 ( 1398 )
- 分类: