Java HTTP客户端请求设置超时时间。

3
我想设置请求的超时时间。这是我目前的代码。
final HttpClient httpclient = HttpClients.createDefault();
final HttpPost httppost = new HttpPost(address);
httppost.setHeader("Accept", "text/xml");
httppost.setHeader("Content-type", "application/xml; charset=UTF-8");
httppost.setEntity(new StringEntity(body));
final HttpResponse response = httpclient.execute(httppost);
final HttpEntity entity = response.getEntity();

我已经尝试过(不起作用,一直在加载并忽略超时)。

// set the connection timeout value to 30 seconds (30000 milliseconds)
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
client = new DefaultHttpClient(httpParams);

而且(这个会抛出java.lang.UnsupportedOperationException

httpclient = HttpClients.createDefault();
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);

有没有其他设置超时的方法?我不需要真正的响应,因此类似于异步请求之类的东西也可以。


这不对吗?final HttpClient httpclient; = HttpClients.createDefault(); 你多了一个分号。 - SpringLearner
你尝试过使用 CoreConnectionPNames.TIMEOUT 吗? - christopher
@christopher .TIMEOUT.不存在。 - Niklas
抱歉,我的意思是 ConnManagerPNames.TIMEOUT - christopher
@christopher 然后我再次收到 java.lang.UnsupportedOperationException - Niklas
显示剩余3条评论
1个回答

4

Apache的HttpClient具有两个独立的超时时间:等待建立TCP连接的超时时间和等待下一个数据字节的超时时间。

HttpConnectionParams.setConnectionTimeout()用于建立TCP连接,而HttpConnectionParams.setSoTimeout()用于等待下一个数据字节时的超时。

// Creating default HttpClient
HttpClient httpClient = new DefaultHttpClient();
final HttpParams httpParams = httpClient.getParams();

// Setting timeouts
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 30000);

// Rest of your code
final HttpPost httppost = new HttpPost(address);
httppost.setHeader("Accept", "text/xml");
httppost.setHeader("Content-type", "application/xml; charset=UTF-8");
httppost.setEntity(new StringEntity(body));
final HttpResponse response = httpclient.execute(httppost);
final HttpEntity entity = response.getEntity();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接