java 中如何给http 设置超时请求

java 中网络发送的请求超时如何设置?

ConnManagerParams.setTimeout(params, 1000);

我查到的这个方法已经被废弃了,我的代码

headers.add(new BasicHeader("User-Agent", "Mozilla/5.0(Windows NT 6.1;Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"));
headers.add(new BasicHeader("Referer", "https://gongshang.mingluji.com/beijing/"));
HttpClientBuilder httpClient = HttpClientBuilder.create().setDefaultHeaders(headers);
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.build().execute(httpGet);
TimeUnit.SECONDS.sleep(SleepTime);
HttpEntity httpEntity = response.getEntity();
ResponseBody = EntityUtils.toString(httpEntity, "utf-8");
阅读 5.8k
2 个回答

如果是使用apache的httpclient发送http请求,请求的超时时间是通过socket设置的,可参考如下代码:

 CloseableHttpClient client = HttpClients.custom()
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectTimeout(500) //连接超时时间,单位毫秒,按实际情况调整
                    .build())
            .setDefaultSocketConfig(SocketConfig.custom()
                    .setSoTimeout(2 * 1000) //请求响应超时时间,单位毫秒,这里设为2秒,按实际情况调整
                    .build())
            .build();
新手上路,请多包涵

RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(500000).setConnectionRequestTimeout(100000).setSocketTimeout(500000).build();
httpGet.setConfig(requestConfig);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题