[英]connection persistence using httpclient
i do multiple request to the same url using httpclient.execute(request). 我使用httpclient.execute(请求)对同一个URL执行多个请求。 Can I re-use the connection for the consecutive requests? 我可以为连续请求重新使用连接吗? how can i optimise the code without declaring HttpClient again and again. 如何在不重复声明HttpClient的情况下优化代码。
for(int i=0;i<=50;i++)
{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("my_url");
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
}
In order to use a single client in your code (based on Exception using HttpRequest.execute(): Invalid use of SingleClientConnManager: connection still allocated and Lars Vogel Apache HttpClient - Tutorial ): 为了在你的代码中使用单个客户端(基于Exception使用HttpRequest.execute():无效使用SingleClientConnManager:仍然分配连接和Lars Vogel Apache HttpClient - 教程 ):
for-loop
. 步骤1.将客户端生成移动到for-loop
。 Step 2. You should read the response content and close the stream. 步骤2.您应该阅读响应内容并关闭流。 If you don't do this you will get the following exception 如果您不这样做,您将收到以下异常
Exception in thread "main" java.lang.IllegalStateException: Invalid use of SingleClientConnManager: connection still allocated.
In code: 在代码中:
//step 1
HttpClient client = new DefaultHttpClient();
for(int i=0;i<=50;i++) {
HttpGet request = new HttpGet("my_url");
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
//step 2
BufferedReader br = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
//since you won't use the response content, just close the stream
br.close();
}
try below. 试试下面。
HttpUriRequest httpGet = new HttpGet(uri);
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.