httpClient设置超时时间

httpClient设置超时时间

简介

httpClient各个版本的API都有很大差别,这里介绍的是4.5版本的超时时间设置。之前百度有的说httpClient超时时间最大20秒,但是我测试的不是的,只要原网址没有说超时,使用httpClient发送的请求设置的超时时间就有效

如果本来的网址超时时间在20秒之内,那么使用httpClient发送请求设置超时大于原网址是无效的

		
		CloseableHttpClient client = HttpClients.createDefault();
		//httpClient配置
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000)		//设置连接超时时间
                .setSocketTimeout(60000).build();		//设置响应超时时间
        System.out.println(System.currentTimeMillis());
        //设置一个不可能请求到的网址
        HttpGet httpGet = new HttpGet("http://123.123.123.123");
        //将配置设置到里面
        httpGet.setConfig(config);
        HttpResponse res = client.execute(httpGet);
        System.out.println(System.currentTimeMillis());

如果是post请求也是一样的,下面是讲一下302请求如果中间有需要的cookie之类的东西怎么解决,首先post请求本身遇到302请求就不会继续请求,但是get请求需要设置

		CloseableHttpClient client = HttpClients.createDefault();
		//httpClient配置 设置不自动跳转
        RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).build();
        System.out.println(System.currentTimeMillis());
        //设置一个不可能请求到的网址
        HttpGet httpGet = new HttpGet("http://123.123.123.123");
        //将配置设置到里面
        httpGet.setConfig(config);
        HttpResponse res = client.execute(httpGet);
        System.out.println(System.currentTimeMillis());

版权声明:本文为zhang_m_h原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。