Java HTTP客户端请求设置超时

时间:2014-04-01 11:55:36

标签: java

我想设置请求的超时。这是我到目前为止的代码。

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);

还有其他设置时间的方法吗?我真的不需要响应,所以像异步请求这样的东西也可以完成这项工作。

1 个答案:

答案 0 :(得分: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();