http 可以添加超时时间,防止超时问题

  • Post author:
  • Post category:其他


1、http请求,很容易网络抖动,所以加上超时可以解决这种问题

 public static String doHttpPost(String uri, JSONObject jsonObject) {
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(uri);
            CloseableHttpClient httpClient = HttpClients.createDefault();

            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(1000) //连接超时时间
                    .setConnectionRequestTimeout(1000) //从连接池中取的连接的最长时间
                    .setSocketTimeout(1000) //数据传输的超时时间
                    .build();
            //设置请求配置时间
            httpPost.setConfig(config);

            //装填参数
            StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            //设置参数到请求对象中
            httpPost.setEntity(s);
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            response = httpClient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("statusCode:" +statusCode );
            if (HttpStatus.SC_OK == statusCode) {
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    String resStr = EntityUtils.toString(entity, "utf-8");
                    return resStr;
                }
            }
        } catch (Exception e) {
            System.out.println("CloseableHttpClient-post-请求异常:" + e.getMessage()+",case" +String.valueOf(e.getStackTrace()));
        } finally {
            try {
                if (null != response) {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

2、嵌入springboot服务相关代码优化参数


import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import java.util.*;

@Slf4j
public class HttpClientUtils {

    private final static HttpClientBuilder httpClientBuilder = HttpClients.custom();
    static {
        //https 协议工厂
        SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(SSLContexts.createSystemDefault(),
                new String[]{"TLSv1.2"},
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());

         //创建注册对象
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https",sslFactory)
                .build();
        //创建连接池
        //创建 ConnectionManager 接口 new (连接池)
        PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager(registry);
        //设置连接池最大连接数
        pool.setMaxTotal(20);
        //设置每个路由默认多少链接
        pool.setDefaultMaxPerRoute(20);
        //设置连接池属性
        httpClientBuilder.setConnectionManager(pool);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000 * 90) // 创建链接 (TCP协议的三次握手)超时时间
                .setSocketTimeout(1000 * 90) // 响应 获取响应内容 超时时间
                .setConnectionRequestTimeout(1000 * 30) // 从链接池 获取链接的超时时间
                .build();

        httpClientBuilder.setDefaultRequestConfig(requestConfig);

        //设置默认的请求头
        List<Header> headerList = new ArrayList<>();
        BasicHeader header = new BasicHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.78");
        headerList.add(new BasicHeader("Content-Type","application/json"));
        headerList.add(new BasicHeader("Accept", "application/json"));
        headerList.add(header);
        httpClientBuilder.setDefaultHeaders(headerList);
        //设置连接池为共享的
        httpClientBuilder.setConnectionManagerShared(true);

    }

    public static String doPost(String url, String body, Map<String,String> header)  {
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = httpClientBuilder.build();
        try{
            HttpPost httpPost = new HttpPost(url);
            //设置请求头
            if (header != null && header.size() > 0) {
                Iterator<Map.Entry<String, String>> iterator = header.entrySet().iterator();
                while(iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(),next.getValue());
                }
            }

            StringEntity jsonEntity = new StringEntity(body);
            jsonEntity.setContentType("application/json;charset=UTF-8");
            jsonEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            jsonEntity.setContentEncoding(Consts.UTF_8.name());
            httpPost.setEntity(jsonEntity);

            response = httpClient.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() == HttpStatus.SC_OK){
                HttpEntity responseEntity = response.getEntity();
                if (null != responseEntity) {
                    String resStr = EntityUtils.toString(responseEntity, "utf-8");
                    return resStr;
                }
            }
        }catch (Exception e) {
            log.warn("CloseableHttpClient-post-请求异常:{},case:{}",e.getMessage(),e.getStackTrace());
            e.printStackTrace();
        }finally {
            try {
                //关闭response请求
                if (null != response) {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                }
                //关闭httpClient
                org.apache.http.client.utils.HttpClientUtils.closeQuietly(httpClient);
            }catch (Exception e){
                log.warn("httpclient close exception:{}",e.getStackTrace());
            }
        }
        return null;
    }

}

3、调用方式

String responseStr = HttpClientUtils.doPost(centerCasServerUrlPrefix+UrlConstant.CENTER_OA_AUTHORIZE, requestMap.toString(),headerMap);



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