简体   繁体   中英

Java HTTP Client request set timeout

I want to set the timeout of a request. This is the code, I've got so far.

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

I've tried (does not work, keeps loading and ignores timeout)

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

and (this one throws java.lang.UnsupportedOperationException )

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

Is there any other way for setting the timout? I don't really need the response so something like an asynchronous request could do the work too.

Apache's HttpClient has two separate timeouts: a timeout for how long to wait to establish a TCP connection, and a separate timeout for how long to wait for a subsequent byte of data.

HttpConnectionParams.setConnectionTimeout() is used for establishing a TCP connection, whereas HttpConnectionParams.setSoTimeout() is used while waiting for a subsequent byte of data.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM