httpclient-3.1.0.jar:异常 java.net.ConnectException: Connection refused

问题现象

java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:327)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:193)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)

 

问题原因

com.springsource.org.apache.commons.httpclient-3.1.0.jar 相比commons-httpclient-3.0.jar 对 SimpleHttpConnectionManager对象做了变更,增加了alwaysClose属性,默认值为false

 

源码: SimpleHttpConnectionManager

  //默认为false
    private boolean alwaysClose = false;

    /**
     * The connection manager created with this constructor will try to keep the 
     * connection open (alive) between consecutive requests if the alwaysClose 
     * parameter is set to <tt>false</tt>. Otherwise the connection manager will 
     * always close connections upon release.
     * 
     * @param alwaysClose if set <tt>true</tt>, the connection manager will always
     *    close connections upon release.
     */
    public SimpleHttpConnectionManager(boolean alwaysClose) {
        super();
        this.alwaysClose = alwaysClose;
    }
    
    /**
     * The connection manager created with this constructor will always try to keep 
     * the connection open (alive) between consecutive requests.
     */
    public SimpleHttpConnectionManager() {
        super();
    }

使用HttpClient 的时候经常使用下面的代码

//旧代码实现
HttpClient client = new HttpClient();  //HttpClient 通过无参构造实现
HttpMethod method = new GetMethod("http://www.apache.org");  
try {  
  client.executeMethod(method);  
  byte[] responseBody = null;  
    
  responseBody = method.getResponseBody();  
    
} catch (HttpException e) {  
  // TODO Auto-generated catch block  
  e.printStackTrace();  
} catch (IOException e) {  
  // TODO Auto-generated catch block  
  e.printStackTrace();  
}finally{  
  method.releaseConnection();  
    
}


//其中new HttpClient() 构造器处理过程
public HttpClient() {
    this(new HttpClientParams());
}

public HttpClient(HttpClientParams params) {
     super();
     if (params == null) {
         throw new IllegalArgumentException("Params may not be null");  
     }
     this.params = params;
     this.httpConnectionManager = null;
     Class clazz = params.getConnectionManagerClass();
     if (clazz != null) {
        try {
            this.httpConnectionManager = (HttpConnectionManager) clazz.newInstance();
        } catch (Exception e) {
                LOG.warn("Error instantiating connection manager class, defaulting to"
                    + " SimpleHttpConnectionManager", 
                    e);
       }
     }
     if (this.httpConnectionManager == null) {
        //这是会使用无参构造器
        this.httpConnectionManager = new SimpleHttpConnectionManager();
     }
     if (this.httpConnectionManager != null) {
        this.httpConnectionManager.getParams().setDefaults(this.params);
     }
}

 

可见 创建SimpleHttpConnectionManager时this.httpConnectionManager = new SimpleHttpConnectionManager(); 使用无参构造器, 这个时候alwaysClose是false

当使用 method.releaseConnection(); 关闭链接时,GetMethod调用releaseConnection()实际上是调用父类同名方法,需要判断alwaysClose=true才能执行关闭,因这个原因报问题异常

HttpMethodBase源码:
    public void releaseConnection() {
        try {
            if (this.responseStream != null) {
                try {
                    // FYI - this may indirectly invoke responseBodyConsumed.
                    this.responseStream.close();
                } catch (IOException ignore) {
                }
            }
        } finally {
            ensureConnectionRelease();
        }
    }

   private void ensureConnectionRelease() {
        if (responseConnection != null) {
            responseConnection.releaseConnection();
            responseConnection = null;
        }
    }

HttpConnection源码:
    public void releaseConnection() {
        LOG.trace("enter HttpConnection.releaseConnection()");
        if (locked) {
            LOG.debug("Connection is locked.  Call to releaseConnection() ignored.");
        } else if (httpConnectionManager != null) {
            LOG.debug("Releasing connection back to connection manager.");
            httpConnectionManager.releaseConnection(this);
        } else {
            LOG.warn("HttpConnectionManager is null.  Connection cannot be released.");
        }
    }

 SimpleHttpConnectionManager源码:
    public void releaseConnection(HttpConnection conn) {
        if (conn != httpConnection) {
            throw new IllegalStateException("Unexpected release of an unknown connection.");
        }

        //这里判断alwaysClose=true的时候才会close,但是现在是false 所以无法正常关闭
        if (this.alwaysClose) {
            httpConnection.close();
        } else {
            // make sure the connection is reuseable
            finishLastResponse(httpConnection);
        }
        
        inUse = false;

        // track the time the connection was made idle
        idleStartTime = System.currentTimeMillis();
    }

处理方式

因为com.springsource.org.apache.commons.httpclient-3.1.0.jar 相比commons-httpclient-3.0.jar 对 SimpleHttpConnectionManager对象做了变更

构造 HttpClient的方式不同,建议使用 HttpClient httpClient = new HttpClient(new HttpClientParams(),new SimpleHttpConnectionManager(true)); 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
// JBuilder API Decompiler stub source generated from class file // 2010-1-15 // -- implementation of methods is not available package org.apache.commons.httpclient; // Imports import java.io.IOException; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.logging.Log; public class HttpClient { // Fields private static final Log LOG; private HttpConnectionManager httpConnectionManager; private HttpState state; private HttpClientParams params; private HostConfiguration hostConfiguration; // Constructors public HttpClient() { } public HttpClient(HttpClientParams params) { } public HttpClient(HttpClientParams params, HttpConnectionManager httpConnectionManager) { } public HttpClient(HttpConnectionManager httpConnectionManager) { } // Methods public synchronized HttpState getState() { return null;} public synchronized void setState(HttpState state) { } public synchronized void setStrictMode(boolean strictMode) { } public synchronized boolean isStrictMode() { return false;} public synchronized void setTimeout(int newTimeoutInMilliseconds) { } public synchronized void setHttpConnectionFactoryTimeout(long timeout) { } public synchronized void setConnectionTimeout(int newTimeoutInMilliseconds) { } public int executeMethod(HttpMethod method) throws IOException, HttpException { return 0;} public int executeMethod(HostConfiguration hostConfiguration, HttpMethod method) throws IOException, HttpException { return 0;} public int executeMethod(HostConfiguration hostconfig, HttpMethod method, HttpState state) throws IOException, HttpException { return 0;} public String getHost() { return null;} public int getPort() { return 0;} public synchronized HostConfiguration getHostConfiguration() { return null;} public synchronized void setHostConfiguration(HostConfiguration hostConfiguration) { } public synchronized HttpConnectionManager getHttpConnectionManager() { return null;} public synchronized void setHttpConnectionManager(HttpConnectionManager httpConnectionManager) { } public HttpClientParams getParams() { return null;} public void setParams(HttpClientParams params) { } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

=PNZ=BeijingL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值