• 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

  • 相关阅读:
    mysql 业务SQL语句使用记录
    expect脚本使用
    ActiveMQ消息队列集群搭建
    使用Helm部署dashboard(更换默认helm仓库)
    2008 R2中的无线连接 wireless
    多线程下的单例设计模式
    如何思索算法(一)
    提问的智慧 整理版
    如何思索算法(三)动态规划
    如何思索算法(二) 谈谈素数
  • 原文地址:https://www.cnblogs.com/DreamFather/p/11327991.html
Copyright © 2020-2023  润新知