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。

学海无涯苦作舟!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值