httclient caught when connecting to the target host:Address already in use

本文介绍了四种有效管理HTTP连接的方法,包括客户端主动关闭TCP连接及服务器端自动关闭连接的技术细节。通过实例展示了如何利用不同的方法来控制连接的生命周期,提高应用程序的性能。

转自:http://seanhe.iteye.com/blog/234759

方法一: 
把事例代码中的第一行实例化代码改为如下即可,在method.releaseConnection();之后connection manager会关闭connection 。 

Java代码 
  1. HttpClient client = new HttpClient(new HttpClientParams(),new SimpleHttpConnectionManager(true) );  


方法二: 
实例化代码使用:HttpClient client = new HttpClient(); 
在method.releaseConnection();之后加上 

Java代码 
  1. ((SimpleHttpConnectionManager)client.getHttpConnectionManager()).shutdown();  


shutdown源代码很简单,看了一目了然 

Java代码 
  1. public void shutdown() {  
  2.     httpConnection.close();  
  3. }  


方法三: 
实例化代码使用:HttpClient client = new HttpClient(); 
在method.releaseConnection();之后加上 
client.getHttpConnectionManager().closeIdleConnections(0);此方法源码代码如下: 

Java代码 
  1. public void closeIdleConnections(long idleTimeout) {  
  2.     long maxIdleTime = System.currentTimeMillis() - idleTimeout;  
  3.     if (idleStartTime <= maxIdleTime) {  
  4.         httpConnection.close();  
  5.     }  
  6. }  


将idleTimeout设为0可以确保链接被关闭。 
以上这三种方法都是有客户端主动关闭TCP链接的方法。下面再介绍由服务器端自动关闭链接的方法。 
方法四: 
代码实现很简单,所有代码就和最上面的事例代码一样。只需要在HttpMethod method = new GetMethod("http://www.apache.org");加上一行HTTP头的设置即可 

Java代码 
  1. method.setRequestHeader("Connection""close");  

看一下HTTP协议中关于这个属性的定义: 
HTTP/1.1 defines the "close" connection option for the sender to signal that the connection will be closed after completion of the response. For example, 
       Connection: close

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值