谷歌提供的HttpURLConnection使用2个不同的例子 - 我们应该呼吁的HttpURLConnection的断开,或InputStream中的亲密? [英] Google provides 2 different examples of HttpURLConnection usage - Should we call HttpURLConnection's disconnect, or InputStream's close?

查看:357
本文介绍了谷歌提供的HttpURLConnection使用2个不同的例子 - 我们应该呼吁的HttpURLConnection的断开,或InputStream中的亲密?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谷歌将提供的HttpURLConnection 使用2种不同的例子。

电话的InputStream 关闭

<一个href="http://developer.android.com/training/basics/network-ops/connecting.html">http://developer.android.com/training/basics/network-ops/connecting.html

  //给出一个网址,建立了一个HttpURLConnection类和检索
//网页内容作为InputStream的,它返回如
//一个字符串。
私人字符串downloadUrl(字符串myurl)抛出IOException异常{
    InputStream的是= NULL;
    //只有展示的检索到的第一个500个字符
    //网页内容。
    INT LEN = 500;

    尝试 {
        网址URL =新的URL(myurl);
        HttpURLConnection的康恩=(HttpURLConnection类)url.openConnection();
        conn.setReadTimeout(10000 / *毫秒* /);
        conn.setConnectTimeout(15000 / *毫秒* /);
        conn.setRequestMethod(GET);
        conn.setDoInput(真正的);
        //开始查询
        conn.connect();
        INT响应= conn.getResponse code();
        Log.d(DEBUG_TAG的反应是:+响应);
        是= conn.getInputStream();

        //将InputStream的成字符串
        字符串contentAsString = readIt(就是LEN);
        返回contentAsString;

    //使确认的InputStream关闭后的应用程序是
    //使用完毕。
    } 最后 {
        如果(是!= NULL){
            is.close();
        }
    }
}
 


电话的HttpURLConnection 断开

<一个href="http://developer.android.com/reference/java/net/HttpURLConnection.html">http://developer.android.com/reference/java/net/HttpURLConnection.html

 网​​址URL =新的URL(http://www.android.com/);
   HttpURLConnection的的URLConnection =(HttpURLConnection类)url.openConnection();
   尝试 {
     InputStream的时间=新的BufferedInputStream(urlConnection.getInputStream());
     readStream(在);
    最后 {
     urlConnection.disconnect();
   }
 }
 


对于资源泄漏性能考虑(不需要从地面安装的网络连接起来,因为我的应用程序将与同一个服务器的大部分时间沟通),我们是否应该

  1. 呼叫的HttpURLConnection 断开只。
  2. 致电的InputStream 关闭只。
  3. 在通话双方的HttpURLConnection 断开&放大器; 的InputStream 关闭(没见过到目前为止这种官方的例子)。
解决方案

根据Oracle的Java,调用<一href="http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#disconnect%28%29"><$c$c>disconnect()可能关闭基础套接字连接,如果连接处于空闲状态(不取任何东西)。这表明,其他请求到服务器不太可能在不久的将来使用相同的的HttpURLConnection 实例。你将不得不重新创建一个新的套接字连接另一个的HttpURLConnection

不过,谷歌已经修改的HttpURLConnection 使套接字连接可重复使用。在Android中,底层的插槽使用的的HttpURLConnection 可能被持久保存并重复使用多个请求。如果你调用断开完成您的请求后,它可以发送插座包含其他空闲连接池,随时可以重复使用。该系统这样做是为了减少等待时间。

在<一个href="http://developer.android.com/reference/java/net/HttpURLConnection.html#disconnect%28%29">documentation:

  

与其他Java实现,这并不一定会关闭   套接字连接,可以重复使用。您可以禁用所有的连接   由http.keepAlive系统属性设置为false之前重用   发出任何HTTP请求。​​

所以,你应该叫断开来释放资源(数据流和插座),但有些发布资源的可以的重复使用(即插座将进入空闲套,准备下一个的HttpURLConnection 实例重用它)池。

至于为什么第一个例子中没有叫断开连接(),即重用连接的Java SE的方式(我认为,它已经有一段时间)。什么是笔者所做的是手动关闭连接的的InputStream 和左座开放和空闲重用。第二个示例显示在Android上的正确方法。

总结:调用断开连接()在Android将关闭任何的InputStream 的OutputStream 用于连接的可以的发送用于连接到池插槽,随时可以再用于其他请求。所以,如果你调用断开连接(),没有必要调用的InputStream#关闭()

Google is providing 2 different examples of HttpURLConnection usage.

Calling InputStream's close

http://developer.android.com/training/basics/network-ops/connecting.html

// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

    // Makes sure that the InputStream is closed after the app is
    // finished using it.
    } finally {
        if (is != null) {
            is.close();
        } 
    }
}


Calling HttpURLConnection's disconnect

http://developer.android.com/reference/java/net/HttpURLConnection.html

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


For resource leakage and performance consideration (Need not to setup network connection from ground up, as my app will communicate with same server most of the time), should we

  1. Call HttpURLConnection's disconnect only.
  2. Call the InputStream's close only.
  3. Call both HttpURLConnection's disconnect & InputStream's close (Haven't seen such official example so far).

解决方案

According to Oracle's Java, calling the disconnect() may close the underlying socket connection, if the connection is idle (not fetching anything). This "indicates that other requests to the server are unlikely in the near future" using that same HttpUrlConnection instance. You will have to reopen a new socket connection by creating another HttpUrlConnection.

However, Google has modified HttpUrlConnection so that socket connections can be reused. In Android, the underlying Socket used by a HttpUrlConnection may be persisted and reused for multiple requests. If you call disconnect after completing your request, it may send the socket to a pool containing other idle connections, ready to be reused. The system does this to reduce latency.

From the documentation:

Unlike other Java implementations, this will not necessarily close socket connections that can be reused. You can disable all connection reuse by setting the http.keepAlive system property to false before issuing any HTTP requests.

So you should call disconnect to release resources (streams and sockets), but some of the resources released may be reused (i.e. the socket will go into a pool of idle sockets, ready for the next HttpUrlConnection instance to reuse it).

As for why the first example did not call disconnect(), that is the Java SE way of reusing the connection (I think, it's been a while). What the author did was manually close the InputStream of the connection and left the socket open and idle for reuse. The second example shows the correct way on Android.

In summary: calling disconnect() on Android will close any InputStream or OutputStream used for the connection and may send the socket used for the connection to a pool, ready to be reused for other requests. So, if you call disconnect(), there is no need to call InputStream#close().

这篇关于谷歌提供的HttpURLConnection使用2个不同的例子 - 我们应该呼吁的HttpURLConnection的断开,或InputStream中的亲密?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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