Java 避免每次使用后都关闭DefaultHttpClient()的解决方法

Java 避免每次使用后都关闭DefaultHttpClient()的解决方法,java,httpclient,Java,Httpclient,每次执行Http请求时,我都会调用此方法 private JSONObject getRequest(HttpUriRequest requestType) { httpClient = new DefaultHttpClient(); // Creating an instance here try { httpResponse = httpClient.execute(requestType); if (htt

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

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

所以每次我创建
新的DefaultHttpClient()
对象并在使用后关闭它时。如果我不关闭它,我的应用程序(Android)就会有很多问题。我有一种预感,这不是最便宜的操作,我需要以某种方式改进它。是否可以以某种方式刷新连接,这样我就不需要每次调用shutdown方法

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

只需确保在执行每个请求后,都会清除响应对象中的实体。比如:

        // 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();

顺便说一句,如果你不关闭连接管理器,你会遇到什么样的问题。

如果我不关闭连接管理器,我将无法生成其他请求,甚至应该重新启动设备上的Wifi连接。请按照示例程序中给出的模式进行操作,并进行检查。注意,ApacheHttpClient
consumeContent
的4.1及更高版本已经被弃用。现在应该使用
EntityUtils.consume(response.getEntity())
。看见