每次我执行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
}
}
Run Code Online (Sandbox Code Playgroud)
所以每次我创建new DefaultHttpClient()对象并在使用后关闭它.如果我不关闭它,我的应用程序(Android)有很多麻烦.我有一个预感,这不是最便宜的操作,我需要以某种方式改善这一点.是否有可能以某种方式刷新连接,所以我不需要每次都调用shutdown方法?
我确信您可以在处理请求后重复使用相同的httpClient对象.您可以查看本程序以查看参考代码.
只需确保在执行每个请求后,清除响应对象上的实体.就像是:
// 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();
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果你不关闭连接mgr,你会遇到什么样的问题.