zoukankan      html  css  js  c++  java
  • HttpClient 如何设置超时时间

    今天分享一个巨坑,就是 HttpClient。这玩意有多坑呢?就是每个版本都变,近日笔者深受其害。
    先看一下代码,我要发送请求调用一个c++接口。

    public static String doPostWithJSON(String url, String json) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
        StringEntity se = new StringEntity(json,  Charset.forName("UTF-8"));
        se.setContentType("application/json");
        httpPost.setEntity(se);
        CloseableHttpResponse response =  client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        return result;
    }
    

    嗯,坑爹的地方来了,这个玩意发送请求,没设置超时时间,只要不响应,他能一直在这等着,这谁能受得了。
    我要加个超时时间。
    第二个大坑来了。
    我记得以前设置超时时间是这样的。

    client.setConnectionTimeout(10000); 
    client.setTimeout(10000);
    

    我发现,特么没这个方法。
    于是查阅资料。发现HttpClient太善变了。每个版本都变api。
    4.3版本是这样的

    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,10000);
    
    

    4.3以后是这样的。

    RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
    httpGet.setConfig(requestConfig);
    

    最后我根据我的版本,选了4.3的那种方式,解决问题。

  • 相关阅读:
    寒号鸟不是鸟,爸爸你会吃。
    思杨的课外班的思考
    一年级第二学期
    City
    SON
    python(16)——生成器
    python(15)——迭代和迭代器
    python(14)——python中的数学模块
    python(13)——lambda表达式
    Python(12)——变量作用域及闭包操作
  • 原文地址:https://www.cnblogs.com/jichi/p/11331485.html
Copyright © 2011-2022 走看看