java 每次使用后不关闭 DefaultHttpClient() 的解决方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4728683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Workaround to not shutdown DefaultHttpClient() each time after usage
提问by Eugene
Each time I do a Http request I invoke this method
每次我做一个 Http 请求时,我都会调用这个方法
private JSONObject getRequest(HttpUriRequest requestType) {
httpClient = new DefaultHttpClient(); // Creating an instance here
try {
httpResponse = httpClient.execute(requestType);
if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200) {
httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
InputStream instream = httpEntity.getContent();
String convertedString = convertStreamToString(instream);
return convertToJSON(convertedString);
} else return null;
} else return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
httpClient.getConnectionManager().shutdown(); // Close the instance here
}
}
So each time I create new DefaultHttpClient()
object and close it after usage. If I don't close it I have numerous troubles with my application (Android). I have a foreboding this is not the cheapest operation and I need to improve this somehow. Is it possible to flush the connection somehow so I don't need to call shutdown method each time?
所以每次我创建new DefaultHttpClient()
对象并在使用后关闭它。如果我不关闭它,我的应用程序(Android)就会遇到很多麻烦。我有预感这不是最便宜的操作,我需要以某种方式改进它。是否可以以某种方式刷新连接,这样我就不需要每次都调用关闭方法?
回答by cheekoo
I am sure you can re-use the same httpClient object after processing a request. You can look at This Programto see a reference code.
我相信您可以在处理请求后重新使用相同的 httpClient 对象。您可以查看本程序以查看参考代码。
Just make sure after each request is executed, you clean entities off the response object. Something like:
只需确保在执行每个请求后,清除响应对象中的实体即可。就像是:
// Must call this to release the connection
// #1.1.5 @
// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
HttpEntity enty = response.getEntity();
if (enty != null)
enty.consumeContent();
BTW, what kind of issues are you getting into, if you dont shutdown the connection mgr.
顺便说一句,如果您不关闭连接管理器,您会遇到什么样的问题。