2012-11-28 46 views
4

嚴格模式會投訴以下內容:資源是在附加的堆棧跟蹤中獲取的,但從未發佈。見java.io.Closeable的信息,避免資源泄漏:嚴格模式對資源泄漏抱怨

**response = httpclient.execute(httpPost);** 

下面是我的代碼:

HttpClient httpclient = new DefaultHttpClient(); 

    String url = "example"; 
    HttpPost httpPost = new HttpPost(url); 

    HttpResponse response; 
    String responseString = ""; 
    try { 
     httpPost.setHeader("Content-Type", "application/json"); 

**response = httpclient.execute(httpPost);** 

     StatusLine statusLine = response.getStatusLine(); 
     if (statusLine.getStatusCode() == HttpStatus.SC_OK) { 
      ByteArrayOutputStream out = new ByteArrayOutputStream(); 
      response.getEntity().writeTo(out); 
      out.close(); 
      responseString = out.toString(); 
     } else { 
      response.getEntity().getContent().close(); 
      throw new IOException(statusLine.getReasonPhrase()); 
     } 
    } catch (ClientProtocolException e) { 
    } catch (IOException e) { 
    } 

    return responseString; 

在此先感謝。

+2

你關閉你的HTTP客戶端上的最終塊...'的HttpClient .getConnectionManager()。shutdown(); ...' –

+0

感謝大家。 – muneikh

回答

4

由於Praful Bhatanagar指出的那樣,你需要釋放資源最後塊:

HttpClient httpclient = new DefaultHttpClient(); 
//... code skipped 
String responseString = ""; 
try { 
//... code skipped 
} catch (IOException e) { 
} finally { 
    httpClient.getConnectionManager().shutdown(); 
} 
+0

感謝這工作得很好! –

+1

不推薦使用類型爲HttpClient的getConnectionManager()方法 – msysmilu

4

對於4.3的方法所指出的kenota已被棄用。

相反的HttpClient你現在應該使用CloseableHttpClient如下圖所示:

CloseableHttpClient client= HttpClientBuilder.create().build(); 

然後你就可以使用其關閉:

client.close(); 
+0

[無法找到它](http://developer.android.com/reference/packages.html#q=CloseableHttpClient)在文檔中,是否有鏈接? –

+2

[Apache文檔](http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/CloseableHttpClient.html) - Apparrent Android實際上並未使用Apache HTTP的特定發佈版本([source](http://stackoverflow.com/questions/2618573/what-version-of-apache-http-client-is-bundled-in-android-1-6))。我猜這意味着可以使用kenota提到的棄用方法(雖然我沒有真正測試過)。 – Tspoon

+0

爲什麼'HttpClient'接口在關閉時不會有'close'方法? – ADTC