Pergunta

I am receiving the below error message when I execute this code.

A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.:

I am unable to identify the resource leak in the below code. I'll be greatful if anyone point out what actually I am doing wrong.

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();
Foi útil?

Solução

I don't really see any issues with that code, but I recommend closing all the idle connections in the pool.

public abstract void closeIdleConnections (long idletime, TimeUnit tunit)

Furthermore, there are some known issues with the DefaultHttpClient when not entirely configured correctly. I recommend using the AndroidHttpClient as an implementation of the HttpClient interface. Visit following documentation for the explanation:

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top