Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...