开发者

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 co开发者_如何转开发nnection somehow so I don't need to call shutdown method each time?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜