【问题标题】:HttpClient How to set Connection Timeout in individual GetMethodHttpClient如何在单个GetMethod中设置连接超时
【发布时间】:2012-04-23 16:39:18
【问题描述】:

在我的 Web 应用程序中,我有一个全局静态 HttpClient,它用于应用程序的许多部分。它是这样创建的:

MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
params.setConnectionTimeout( 15000 );
params.setSoTimeout( 15000 );
connectionManager.setParams(params);
httpclient = new HttpClient(connectionManager);
HttpClientParams clientParams = new HttpClientParams();
clientParams.setParameter("http.protocol.allow-circular-redirects", true);
clientParams.setParameter("http.protocol.max-redirects", 4);
httpclient.setParams(clientParams);

对于大多数用例来说,超时都很好,但在特定的调用中,我想要更短的超时。所以我有:

GetMethod get = new GetMethod(finalUrl);

get.getParams().setParameter("http.socket.timeout", new Integer(1000));
get.getParams().setParameter("http.connection.timeout", new Integer(1000));
HttpClientUtil.getShortTimeoutInstance().executeMethod(get);

它不起作用。连接超时仍然是15000。我可以在GetMethod中设置特定的连接超时而不创建新的HttpClient实例(这是因为我认为创建一个新的HttpClient实例不是一个好主意)。

【问题讨论】:

    标签: java connection timeout httpclient


    【解决方案1】:

    你可能想看看

    ./impl/conn/tsccm/ThreadSafeClientConnManager.java

    方法

    ClientConnectionRequest requestConnection(final HttpRoute route, 
                                              final Object state)
    

    一旦为路由初始化连接池,最初配置的套接字 timeOut 值将继续使用,除非您扩展/覆盖它。

    public ClientConnectionRequest requestConnection(
            final HttpRoute route,
            final Object state) {
    
        final PoolEntryRequest poolRequest = pool.requestPoolEntry(
                route, state);
    
        return new ClientConnectionRequest() {
    
            public void abortRequest() {
                poolRequest.abortRequest();
            }
    
            public ManagedClientConnection getConnection(
                    long timeout, TimeUnit tunit) throws InterruptedException,
                    ConnectionPoolTimeoutException {
                if (route == null) {
                    throw new IllegalArgumentException("Route may not be null.");
                }
    
                if (log.isDebugEnabled()) {
                    log.debug("Get connection: " + route + ", timeout = " + timeout);
                }
    
                BasicPoolEntry entry = poolRequest.getPoolEntry(timeout, tunit);
                return new BasicPooledConnAdapter(ThreadSafeClientConnManager.this, entry);
            }
    
        };
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多