我应该关闭Android中的HttpURLConnection吗?

时间:2015-09-21 09:40:45

标签: android webview httpurlconnection

我重写以下函数来自行缓存(绕过网络查找)

public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
    // depending on android version, I use the below function
    // public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {

    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();

        in = new BufferedInputStream(urlConnection.getInputStream());
        data = new String(ByteStreams.toByteArray(in));

    } catch (Exception e) {
        return null;
    }

    // do stuff with data but omitted here

    return new WebResourceResponse(mimeType, "UTF-8", in);

}

我没有关闭urlConnection,因为我传递了与urlConnection绑定的输入流。

因为如果你open某事,close它应该是not close,我很担心,如果我对这些代码感到满意,我会很担心。

Do I need to call HttpURLConnection.disconnect after finish using it对此进行了讨论,但我无法在那里获得明确的答案,我们是否被允许{{1}}。

4 个答案:

答案 0 :(得分:1)

一旦读取了响应主体,就应该通过调用disconnect()来关闭HttpURLConnection。断开连接释放连接所拥有的资源,以便它们可以被关闭或重用。

URL url = new URL("http://www.android.com/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
    finally {
     urlConnection.disconnect();
   }
 }

你可以阅读类的使用遵循here

的模式

修改:             看here了解更多

答案 1 :(得分:0)

在返回响应之前,您可以执行以下操作:

final HttpURLConnection connection1 = connection;
in = new BufferedInputStream(connection.getInputStream()){
    @Override
    public void close() throws IOException {
        super.close();
        if (connection1 != null) {
            connection1.disconnect();
        }
    }
};

答案 2 :(得分:0)

也许有点晚了,但我想这就是你想要的。只需使所有可关闭的全局并在onPageFinished中关闭它们。

private class WebViewClientExtends extends WebViewClient {

    // For me it is a inputStream
    // You can define your HttpURLConnection here
    FileInputStream fileInputStream; 

    // Your code here

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        // Same I close my inputStream here
        // You can close your HttpURLConnection here
        if(fileInputStream == null) return;
        try {
            fileInputStream.close();
        } catch (Exception ignore) {
        }
    }
}

将我们自己的扩展类设置为webView,然后完成:

    webView.setWebViewClient(new WebViewClientExtends());

答案 3 :(得分:0)

在我的测试中,无需关闭InputStream。

请参见下面的代码,日志“关闭”已立即打印。

                    if (file.exists()) {
                    InputStream in = new FileInputStream(file) {
                        @Override
                        public void close() throws IOException {
                            super.close();
                            Log.d("zzz", "close");
                        }
                    };
                    return new WebResourceResponse("image/png", "UTF-8", in);