java中持久的Http客户端连接

Aku*_*ete 2 java http

我试图用Java编写一个简单的Http客户端应用程序,并且看似不同的方法来建立Http客户端连接,并有效地重用对象,我感到有点困惑.

目前我正在使用以下步骤(为简单起见,我省略了异常处理)

Iterator<URI> uriIterator = someURIs();

HttpClient client = new DefaultHttpClient();

while (uriIterator.hasNext()) {
   URI uri = uriIterator.next();

   HttpGet request = new HttpGet(uri);

   HttpResponse response = client.execute(request);

   HttpEntity entity = response.getEntity();

   InputStream content = entity.getContent();
   processStream (content );
   content.close();
}
Run Code Online (Sandbox Code Playgroud)

关于上面的代码,我的问题是:

假设所有URI都指向同一主机(但该主机上的资源不同).对所有请求使用单个http连接的推荐方法是什么?

如何在上次请求后关闭连接?

--edit:我很困惑为什么上面的步骤永远不会使用HttpURLConnection,我会假设client.execute()创建一个,但因为我从来没有看到它我不知道如何关闭它或重用它.

ZZ *_*der 6

要有效地使用持久连接,您需要使用池连接管理器,

SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
        new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

ClientConnectionManager cm = new ThreadSafeClientConnManager(schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm);
Run Code Online (Sandbox Code Playgroud)

我对HttpURLConnection的最大问题是它对持久连接的支持(keep-alive)是非常错误的.