Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround to not shutdown DefaultHttpClient() each time after usage

Each time I do a Http request I invoke this method

private JSONObject getRequest(HttpUriRequest requestType) {
        httpClient = new DefaultHttpClient(); // Creating an instance here
        try {
            httpResponse = httpClient.execute(requestType); 
            if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200) {
                httpEntity = httpResponse.getEntity();

                if (httpEntity != null) {
                    InputStream instream = httpEntity.getContent(); 
                    String convertedString = convertStreamToString(instream);
                    return convertToJSON(convertedString);
                } else return null;

            } else return null;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            httpClient.getConnectionManager().shutdown(); // Close the instance here
        }
    }

So each time I create new DefaultHttpClient() object and close it after usage. If I don't close it I have numerous troubles with my application (Android). I have a foreboding this is not the cheapest operation and I need to improve this somehow. Is it possible to flush the connection somehow so I don't need to call shutdown method each time?

like image 337
Eugene Avatar asked Jan 18 '11 20:01

Eugene


1 Answers

I am sure you can re-use the same httpClient object after processing a request. You can look at This Program to see a reference code.

Just make sure after each request is executed, you clean entities off the response object. Something like:

        // Must call this to release the connection
        // #1.1.5 @
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
        HttpEntity enty = response.getEntity();
        if (enty != null)
            enty.consumeContent();

BTW, what kind of issues are you getting into, if you dont shutdown the connection mgr.

like image 90
cheekoo Avatar answered Sep 18 '22 01:09

cheekoo