码迷,mamicode.com
首页 > Web开发 > 详细

apache http调用设置超时时间

时间:2020-04-29 21:50:26      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:ack   握手   config   exe   utf-8   sys   highlight   exception   管理   

 

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调用设置超时时间

标签:ack   握手   config   exe   utf-8   sys   highlight   exception   管理   

原文地址:https://www.cnblogs.com/yaoyu1983/p/12804799.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!