潜在的资源泄漏:在此位置可能无法关闭“ httpclient”

时间:2018-07-17 07:12:36

标签: java memory-leaks eclipse-oxygen

获取标题行中提到的错误

  

返回responseXML.toString();

HttpClient httpclient = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost("test");
httppost.setHeader("Authorization", "test");
httppost.setHeader("content-type", "text/html; charset=UTF-8");
try {
        httppost.setEntity(new UrlEncodedFormEntity(NameValuePairs));
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    HttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream inputStream = null;
    try {
        inputStream = response.getEntity().getContent();
    } catch (IllegalStateException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    BufferedReader bufferReader = new BufferedReader(
            new InputStreamReader(inputStream));

    StringBuffer responseXML = new StringBuffer();
    String line = "";
    try {
        while ((line = bufferReader.readLine()) != null) {
            responseXML.append(line);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        inputStream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println( responseXML.toString());
    return responseXML.toString();

2 个答案:

答案 0 :(得分:0)

您可以使用try-with-sources:try(HttpClient httpClient = new HttpClient) (或从何处获取客户端),也可以在关闭htppClient的地方使用finally:

finally {
httpClient.close();
}

答案 1 :(得分:0)

如前所述,尝试资源应该有帮助。

要利用try-with-resources,您的HttpClient必须为 autocloseable 类型:一种实现java.lang.AutoCloseable的类型。假设您正在使用Apache httpcomponents ...

try(CloseableHttpClient httpclient = HttpClientBuilder.create().build()) {
   // note the CloseableHttpClient which allows this to happen.
}

此模式中代码中还有其他机会,例如您拥有缓冲的读取器。

请参阅此tutorial on try-with-resources