zoukankan      html  css  js  c++  java
  • HttpClient设置连接超时时间

    使用HttpClient,一般都需要设置连接超时时间和获取数据超时时间。这两个参数很重要,目的是为了防止访问其他http时,由于超时导致自己的应用受影响。

    4.5版本中,这两个参数的设置都抽象到了RequestConfig中,由相应的Builder构建,具体的例子如下:

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

      

    setConnectTimeout:设置连接超时时间,单位毫秒。

    setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。

    setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。

    转自:https://www.cnblogs.com/winner-0715/p/7087591.html

  • 相关阅读:
    as
    留言板
    HEOI2020游记
    min_25筛学习笔记
    计算几何初步
    「狗屁不会」exlucas
    GCD of Sequence
    做题记录
    一些奇怪的坑+好东西
    关于我
  • 原文地址:https://www.cnblogs.com/DreamFather/p/11327991.html
Copyright © 2011-2022 走看看