Keep-Alive与HttpURLConnection实现

来源:互联网 发布:视频聚合软件 编辑:程序博客网 时间:2024/06/13 04:06

http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html中的说明:

When the application finishes reading the response body or when the application calls close() on the InputStream returned by URLConnection.getInputStream(), the JDK's HTTP protocol handler will try to clean up the connection and if successful, put the connection into a connection cache for reuse by future HTTP requests.

在完成获取请求返回结果后或调用getInputStream().close(),JDK会清理连接并作为以后使用的连接缓存。不过前提是HTTP header中的Connection值不能为close,否则将被视为该连接不需要持久化。

HttpURLConnection中的disconnect() ,下面是部分源码:

if (inputStream != null) {           HttpClient hc = http;               // un-synchronized              boolean ka = hc.isKeepingAlive();                  try {                    inputStream.close();                } catch (IOException ioe) { }     // if the connection is persistent it may have been closed     // or returned to the keep-alive cache. If it's been returned     // to the keep-alive cache then we would like to close it     // but it may have been allocated                if (ka) {                    hc.closeIdleConnection();                }           } else {       // We are deliberatly being disconnected so HttpClient      // should not try to resend the request no matter what stage       // of the connection we are in.                http.setDoNotRetry(true);                http.closeServer();            }

在调用getInputStream().close()之后,调用disconnet()就不会关闭该连接,连接依然可以复用。只调用disconnet()的话,InputStream与连接都将被关闭。

closeIdleConnection()的源码:

/* * Close an idle connection to this URL (if it exists in the * cache). */public void closeIdleConnection() {    HttpClient http = (HttpClient) kac.get(url, null);    if (http != null) {        http.closeServer();    }}

要达到复用连接的话,调用getInputStream().close()就行,可以不使用disconnect()。

还有一种情况就是当请求异常时,HttpURLConnection提供了getErrorStream()方法可以帮助我们保持连接,官方文档中的例子:

try {    URL a = new URL(args[0]);    URLConnection urlc = a.openConnection();    is = conn.getInputStream();    int ret = 0;    while ((ret = is.read(buf)) > 0) {      processBuf(buf);    }    // close the inputstream    is.close();} catch (IOException e) {    try {            respCode = ((HttpURLConnection)conn).getResponseCode();            es = ((HttpURLConnection)conn).getErrorStream();            int ret = 0;            // read the response body            while ((ret = es.read(buf)) > 0) {                    processBuf(buf);            }            // close the errorstream            es.close();    } catch(IOException ex) {            // deal with the exception    }}
原创粉丝点击