How to release HttpURLConnection bytes?

499 views Asked by At

I´m developing an androi app that sends a lot of http request (HttpURLConnection). Everything is working, but I think my objects are not being released. I say that because when I look at MAT (Eclipse Memory Analyzer) it says I have a lot of byte[] retained. I look into the bytes on MAT and they are the bytes I receive in my HttpURLConnection method. Below is my code for sending http request. Is there anything else I could do to release my objects?

public static String sendHTTPRequest(String requestURL, int timeout) {
    HttpURLConnection httpconn = null;
    try {

        URI uri = new URI(getUTF8Request(requestURL));

        httpconn = (HttpURLConnection) uri.toURL().openConnection();
        httpconn.setConnectTimeout(timeout);
        StringBuilder responseStringBuilder = new StringBuilder();

        if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader input = new BufferedReader(
                    new InputStreamReader(httpconn.getInputStream(),
                            "ISO-8859-1"), 8192);
            String strLine = null;
            while ((strLine = input.readLine()) != null) {
                responseStringBuilder.append(strLine);
            }
            input.close();
            strLine = null;
            input = null;
        }

        return responseStringBuilder.toString();
    } catch (URISyntaxException e) {
        httpconn = null;
        return "Failed to request";
    } catch (IOException e) {
        httpconn = null;
        return "Failed to request";
    } finally {

        requestURL = null;
        if (httpconn != null) {
            httpconn.disconnect();
            httpconn = null;
        }
    }
}
2

There are 2 answers

2
Mr.Me On

In in java you don't have to worry about memory allocation unless it is an issue (outofmemoryexception) android doesn't release memory as soon as your code is done with it, Garbage Collection in android is a bit complicated, and usually doesn't de-allocate allocated memory unless it is necessary to.

0
Diederik On

I notice you won't call httpConnection.disconnect after an IOEcxeption is thrown, as you set it null in the catch block. Obviously then when finally block runs you won't be able to run disconnect on it, an that probably release the bytes that MAT is complaining about.