qq32933432
诺浅
2015-12-28 16:14
采纳率: 100%
浏览 9.6k
已采纳

关于HttpClient设置超时时间无效的问题

超时时间设置60S

超时时间设置60S

超时时间设置5S

超时时间设置5S

可以看到,当把超时时间设置为60S时,依然在21S左右超时,只有当超时时间在21S以下时,才生效。这是什么原因?

public class Send_Class {
    public static int MAX_CONNECTION_PERROUTE = 1;//最大连接数
    public static int SOCKET_TIMEOUT = 60000;//超时时间
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        try {
            String time1= sdf.format(new Date());
            System.out.println(time1);
            Send_Class sc=new Send_Class();
            sc.test();
            time1= sdf.format(new Date());
            System.out.println(time1);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public void test(){
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setDefaultMaxPerRoute(MAX_CONNECTION_PERROUTE);
        Builder builder = RequestConfig.custom();
        RequestConfig config = builder.setSocketTimeout(SOCKET_TIMEOUT)
                .setConnectTimeout(SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(SOCKET_TIMEOUT)
                .setStaleConnectionCheckEnabled(true).build();
        CloseableHttpClient client = HttpClients.custom()
                .setMaxConnPerRoute(MAX_CONNECTION_PERROUTE).disableConnectionState()
                .setDefaultRequestConfig(config)
                .setConnectionManager(cm).build();
        String url="http://128.28.28.28";
        HttpPost post = new HttpPost(url);
        post.setProtocolVersion(HttpVersion.HTTP_1_1);
        post.setConfig(config);
        List<NameValuePair> formpair = new ArrayList<NameValuePair>();
        formpair.add(new BasicNameValuePair("name", "张三"));
        HttpEntity entity = new UrlEncodedFormEntity(formpair, Consts.UTF_8);
        if (entity != null) {
            post.setEntity(entity);
        }
        try {   
            client.execute(post);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • devmiao
    devmiao 2015-12-28 16:52
    已采纳

    httpclient最长只有20秒。你可以用循环增加长度

    点赞 评论
  • qq32933432
    诺浅 2015-12-29 03:49

    没有人吗?没有人来个解释吗?

    点赞 评论

相关推荐