apache http调用设置超时时间
Posted yaoyu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了apache http调用设置超时时间相关的知识,希望对你有一定的参考价值。
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
CloseableHttpClient client = null; HttpRequestBase signedRequest = Client.sign(request); client = HttpClients.custom().build(); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) .setConnectionRequestTimeout(1000).setSocketTimeout(5000).build(); signedRequest.setConfig(requestConfig); HttpResponse response = client.execute(signedRequest); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity resEntity = response.getEntity(); String result = EntityUtils.toString(resEntity, "UTF-8");
CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://www.baidu.com"); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000).setConnectionRequestTimeout(1000) .setSocketTimeout(5000).build(); httpGet.setConfig(requestConfig); CloseableHttpResponse response = null; try { response = httpclient.execute(httpGet); } catch (IOException e) { e.printStackTrace(); } System.out.println("得到的结果:" + response.getStatusLine());//得到请求结果 HttpEntity entity = response.getEntity();//得到请求回来的数据 String s = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(s);
//设置请求超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(2000)
.setConnectionRequestTimeout(2000)
.setSocketTimeout(2000)
.build();
说明
ConnectionRequestTimeout
httpclient使用连接池来管理连接,这个时间就是从连接池获取连接的超时时间,可以想象下数据库连接池
ConnectTimeout
连接建立时间,三次握手完成时间
SocketTimeout
数据传输过程中数据包之间间隔的最大时间
以上是关于apache http调用设置超时时间的主要内容,如果未能解决你的问题,请参考以下文章
httpclient异常“org.apache.http.conn.ConnectionPoolTimeoutException:等待连接超时”
Android 4.0 org.apache.http.conn.ConnectTimeoutException:连接到...超时