标签归档:URLConnection

URLConnection

代码:

  HttpURLConnection conn = null;
  InputStream is = null;
  OutputStream os = null;
  try {
   conn = (HttpURLConnection) new URL(url).openConnection();
   is = conn.getInputStream();
 // code
  } catch (MalformedURLException e) {
  } catch (IOException e) {
  } finally {
   try {
     if (conn != null)
       conn.disconnect();
     if (is != null)
      is.close();
   } catch (IOException e) {
   }
  }
 

在linux下,当连接数多的时候会发现有很多CLOSE_WAIT的连接。windows下好像会好些。

这种情况是因为:在http1.1中所有的conntection默认都是persist Connection(keep-alive)。当Connection.getInputStream() close后,HTTP protocol handler会试图去清理Connection,成功的话会将conntection放入connection缓存,以便下次能重复利用。

修改默认keep-alive:

System.setProperty("http.keepAlive", "false");

修改connection缓存机制:

connection.setUseCaches(false);

参考:Persistent Connections

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6367268

http://stackoverflow.com/questions/4767553/safe-use-of-httpurlconnection

http://hea-www.harvard.edu/~fine/Tech/addrinuse.html