如果在我的应用程序中使用此源代码,则第一次没有问题,但是如果我关闭 wifi 并尝试从 Web 服务获取一些资源,我的应用程序会抛出异常状态:发现泄漏,我使用 httpclient 的关闭方法,但没有任何变化,在使用此代码的两天后,会引发异常。
堆栈打印:
10-17 16:42:00.524: ERROR/AndroidHttpClient(931): Leak found
10-17 16:42:00.524: ERROR/AndroidHttpClient(931): java.lang.IllegalStateException: AndroidHttpClient created and never closed
代码 :
public String getRequest(String url, ArrayList<NameValuePair> nameValuePairs){
String resp = "";
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);
AndroidHttpClient httpclient = null;
try {
httpclient = AndroidHttpClient.newInstance("V");
httpclient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
Reader reader = new InputStreamReader(instream, HTTP.UTF_8);
StringBuilder buffer = new StringBuilder("");
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
reader.close();
resp = buffer.toString().replace(""", "\"");
Log.d("V", "RESPONSE:-----\n" + resp + "\n--------------");
} catch (IOException e){
Log.e("V IOException [Send Request]","IO Exception");
if((e != null) && (e.getMessage() != null)){
Log.e("V",e.getMessage().toString());
}
} catch (Exception e) {
Log.e("V Exception [Send Request]","Exception Requester");
if((e != null) && (e.getMessage() != null)){
Log.e("V",e.getMessage().toString());
}
}finally {
if (httpclient != null && httpclient.getConnectionManager() != null) {
httpclient.close();
httpclient = null;
}
}
return resp;
}