java http 设置timeout,Java:HttpClient 4.1.2:ConnectionTimeout,SocketTimeout值设置无效

在使用HttpClient 4.1.2时,设置连接超时和socket超时并未按预期生效。代码示例中,即使配置了30ms的连接超时和60ms的socket超时,当服务器不可用时,实际超时时间远高于配置值。问题在于HttpConnectionParams需要传递给连接管理器。正确的做法是将超时参数设置到连接管理器,如:httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000); httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000); 这样可以确保超时设置按预期工作。

I am using HttpClient 4.1.2. Setting ConnectionTimeout and SocketTimeout to a value is never effective.

code :

Long startTime = null;

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpParams params = httpClient.getParams();

HttpConnectionParams.setConnectionTimeout(params, 30);

HttpConnectionParams.setSoTimeout(params, 60);

HttpGet httpget = new HttpGet("http://localhost:8080/Test/ScteServer");

try {

startTime = System.currentTimeMillis();

HttpResponse response = httpClient.execute(httpget);

}

catch(SocketTimeoutException se) {

Long endTime = System.currentTimeMillis();

System.out.println("SocketTimeoutException :: time elapsed :: " + (endTime-startTime));

se.printStackTrace();

}

catch(ConnectTimeoutException cte) {

Long endTime = System.currentTimeMillis();

System.out.println("ConnectTimeoutException :: time elapsed :: " + (endTime-startTime));

cte.printStackTrace();

}

catch (ClientProtocolException e) {

e.printStackTrace();

}

catch (IOException e) {

Long endTime = System.currentTimeMillis();

System.out.println("IOException :: time elapsed :: " + (endTime-startTime) );

e.printStackTrace();

}

If the server is down, then the connection timeout is never before 400 ms when it has to timeout at ~ 30 ms as configured.

Same is the case for Socket Timeout, putting a sleep in doGet() for 5000 ms will throw a socket timeout which will never be at around 60 ms as configured. It takes more than 500 ms.

Can anyone suggest how to configure HttpClient 4.1.2 so that it times out around the configured time?

解决方案

The HttpConnectionParams need to be passed to a connection manager (see this question). When using the DefaultHttpClient you can set these parameters like this:

httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);

httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值