1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > java http请求超时问题

java http请求超时问题

时间:2019-12-26 00:22:39

相关推荐

java http请求超时问题

1、案例http请求代码如下:

import org.apache.http.client.CookieStore;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.protocol.HttpClientContext; public static String postBody(String url, String body, Map<String, String> headMap) throws Exception {CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost request = new HttpPost(url);// 配置超时RequestConfig.Builder customReqConf = RequestConfig.custom();customReqConf.setConnectTimeout(5000); //连接超时时间customReqConf.setSocketTimeout(100000);//数据传输的超时时间customReqConf.setConnectionRequestTimeout(5000); //从连接池中取的连接的最长时间request.setConfig(customReqConf.build());CloseableHttpResponse response = null;HttpEntity httpEntity = null;try {request.setHeader("Content-Type", "application/json");if (headMap != null && headMap.size() > 0) {Iterator<String> it = headMap.keySet().iterator();while (it.hasNext()) {String headKey = it.next();request.addHeader(headKey, headMap.get(headKey));}}if (body != null) {StringEntity se = new StringEntity(body, "GBK");request.setEntity(se);}response = httpClient.execute(request);//获得状态码httpEntity = response.getEntity();return EntityUtils.toString(httpEntity);} catch (Exception e) {throw e;} finally {if (httpEntity != null) {EntityUtils.consume(httpEntity);}if (response != null) {response.close();}httpClient.close();}}

这里我们设置了三个超时链接时间。(单位:毫秒)

customReqConf.setConnectTimeout(5000); //连接超时时间

customReqConf.setSocketTimeout(100000); //数据传输的超时时间

customReqConf.setConnectionRequestTimeout(5000); //从连接

对于一般的http请求来说,

设置connectTimeout,与目标url的链接超时时间。超时后会ConnectionTimeOutException。

设置SocketTimeout,是目标链接和当前服务地址数据传输的超时时间,超出后会抛出SocketTimeOutException。为了防止一些耗时响应的操作,可以将这个时间设置的大一些。如果很耗时,可以不设置这个参数,会一直等待数据传输完成。

设置ConnectionRequestTimeout,连接池获取连接的超时时间,如果连接池里连接都被用了,且超过设定时间,就会报错connectionrequesttimeout。

学海无涯苦作舟!!!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。