PhilLab February 2016

How to close a persistent HTTP Connection without reading

I have an URLConnection which I want to cancel depending on the response code without reading any data. I closely followed the android training to build the following minimal example which floods the server with requests since no connection is ever released back to the handle pool for reuse

private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(TAG, "The response code is: " + response);
        is = conn.getInputStream();

        // Do not read anything //String contentAsString = readIt(is, len);
        String contentAsString = "notReadingAnything";
        return contentAsString;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        try {
            String result = new String();
            for (int i=0; i<100; i++) {
                result += downloadUrl(urls[0]);
            }
            return result;
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
    @Override
    protected void onPostExecute(String result) {
        Log.d(TAG, "The response is: " + result);
    }
}

Despite the docs explicitly stat

Answers


Blackbelt February 2016

you should call disconnect() too. Accordingly to the documentation

Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.

InputStream is = null;
HttpURLConnection conn = null;
try {
    URL url = new URL(myurl);
    conn = (HttpURLConnection) url.openConnection();

} finally {
    if (is != null) {
        is.close();
    } 
    if (conn != null) {
        conn.disconnect();
    } 
}

if you still are experiencing issues, is also possible that the bug is backend side

Post Status

Asked in February 2016
Viewed 1,257 times
Voted 10
Answered 1 times

Search




Leave an answer