解决方法是每次使用后都不关闭DefaultHttpClient() [英] Workaround to not shutdown DefaultHttpClient() each time after usage

查看:2927
本文介绍了解决方法是每次使用后都不关闭DefaultHttpClient()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次执行Http请求时,我都会调用此方法

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
        }
    }

所以我每次创建 new DefaultHttpClient() object并在使用后关闭它。如果我不关闭它,我的应用程序(Android)有很多麻烦。我有一个预感,这不是最便宜的操作,我需要以某种方式改善这一点。是否有可能以某种方式刷新连接,所以我不需要每次都调用shutdown方法?

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?

推荐答案

我确信您可以在处理请求后重复使用相同的httpClient对象。您可以查看这程序以查看参考代码。

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,如果你不关闭连接mgr,你会遇到什么样的问题。

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

这篇关于解决方法是每次使用后都不关闭DefaultHttpClient()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆