4

Strict モードでは、次のようにエラーが表示されます:リソースは、添付されたスタック トレースで取得されましたが、解放されませんでした。リソース リークを回避する方法については、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;

前もって感謝します。

4

2 に答える 2

7

4.3 の時点で、kenota によって指摘されたメソッドは非推奨です。

代わりに、以下に示すようにHttpClient使用する必要があります。CloseableHttpClient

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

次に、次を使用して閉じることができます。

    client.close();
于 2014-01-09T20:31:08.350 に答える