1

执行此代码时,我收到以下错误消息。

在附加的堆栈跟踪中获取了资源,但从未释放。有关避免资源泄漏的信息,请参阅 java.io.Closeable。:

我无法识别以下代码中的资源泄漏。如果有人指出我实际上做错了什么,我会很感激。

HttpPost request = new HttpPost(url);
        StringBuilder sb = new StringBuilder();
        StringEntity entity = new StringEntity(jsonString);
        entity.setContentType("application/json;charset=UTF-8");
        entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
        request.setHeader("Accept", "application/json");
        request.setEntity(entity);

        HttpResponse response = null;
        DefaultHttpClient httpclient = getHttpClientImpl();

        BufferedReader reader = null;
        InputStream in = null;
        try {
            response = httpclient.execute(request);
            in = response.getEntity().getContent();
            reader = new BufferedReader(new InputStreamReader(in));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception se) {
            Log.e("Exception", se + "");
            throw se;
        } finally {
            if (in != null)
                in.close();

            if (reader != null)
                reader.close();

            if (client != null && client.getConnectionManager() != null) {
        client.getConnectionManager().shutdown();
    }
        }
        return sb.toString();
4

1 回答 1

1

我真的没有看到该代码有任何问题,但我建议关闭池中的所有空闲连接。

public abstract void closeIdleConnections (long idletime, TimeUnit tunit)

此外,在未完全正确配置的情况下,DefaultHttpClient 存在一些已知问题。我建议使用 AndroidHttpClient 作为 HttpClient 接口的实现。请访问以下文档以获取说明:

http://developer.android.com/reference/android/net/http/AndroidHttpClient.html

于 2012-12-10T11:00:37.790 回答