如题,就是要实现在第一个请求发出之后建立起了连接,那么在该线程中以后的所有请求都使用该连接来进行通信,我理解的同一个连接就是建立连接以后再次发送请求仍然使用上一次的端口号,保证本地端口号和远端端口号的唯一映射(相当于TCP),以后的请求不用new以致产生新的端口映射(大批量请求在每次都new的话会产生异常)!谢谢!最好能给个简单的demo
This is an example of an Apache HttpClient 4.3 pool of connections which do not require authentication:
public class PoolOfHttpConnections{
static String[] urisToGet = {"http://www.site1.com", "http://www.site2.com"};
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
// create a thread for each link
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);
}
// start the threads
for (int j = 0; j < threads.length; j++) {
threads[j].start();
}
// join the threads
for (int j = 0; j < threads.length; j++) {
threads[j].join();
}
} //end main
private 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();
System.out.println("----------------------------------------");
Date date = new Date();
System.out.println("Beginning*******************");
System.out.println(date.toString());
System.out.println("There are "+urisToGet.length+" threads running in parallel!");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println(EntityUtils.toString(entity));
EntityUtils.consume(entity);
} finally {
response.close();
System.out.println("End*******************");
}
} catch (ClientProtocolException ex) {
// Handle protocol errors
} catch (IOException ex) {
// Handle I/O errors
}
}
} /*end private class*/ }//end public class PoolOfHttpConnections
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。