每次使用后不关闭 DefaultHttpClient() 的解决方法
每次我执行 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
}
}
,因此每次我创建 new DefaultHttpClient()
对象并在使用后关闭它。如果我不关闭它,我的应用程序(Android)就会遇到很多麻烦。我有预感这不是最便宜的操作,我需要以某种方式改进它。是否可以以某种方式刷新连接,这样我就不需要每次都调用关闭方法?
Each time I do a Http request I invoke this method
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我确信您可以在处理请求后重新使用相同的 httpClient 对象。你可以看看 这个编程以查看参考代码。
只需确保在执行每个请求后,清除响应对象中的实体即可。比如:
顺便说一句,如果你不关闭连接管理器,你会遇到什么样的问题。
I am sure you can re-use the same httpClient object after processing a request. You can look at This Program to see a reference code.
Just make sure after each request is executed, you clean entities off the response object. Something like:
BTW, what kind of issues are you getting into, if you dont shutdown the connection mgr.