http请求方式-RestTemplate

2024-10-09 10:06:05 浏览数 (1)

http请求方式-RestTemplate

代码语言:javascript复制
import com.alibaba.fastjson.JSON;
import com.example.core.mydemo.http.OrderReqVO;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class RestTemplateTest {

    public static void main(String[] args) {
        //requestVO请求参数
        org.springframework.http.HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-Type", "application/json;charset=UTF-8");
        //            requestHeaders.add("User-Agent", "mysite_web");
        requestHeaders.add("connection", "Keep-Alive");
        //            requestHeaders.add("Accept", "application/json;version=3.0;compress=false");


        OrderReqVO data = new OrderReqVO();
        data.setOrderNum("111123333");
        data.setServerType("1");

        RestTemplate template = new RestTemplate();
        //设置参数
        HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(data), requestHeaders);

        String url = "https://域名/接口名称";

        ResponseEntity<String> response = template.exchange(url,
                HttpMethod.POST, requestEntity, String.class);

        System.out.println("code httpResult="   response.getStatusCode());
        System.out.println("code httpResult="   response.getBody());


    }

}


##方式2
try {
            TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

            SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                    .loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();

            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

            CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(csf)
                    .build();

            HttpComponentsClientHttpRequestFactory requestFactory =
                    new HttpComponentsClientHttpRequestFactory();

            requestFactory.setHttpClient(httpClient);
            RestTemplate restTemplate = new RestTemplate(requestFactory);


            Map<String, Object> map = JSONObject.parseObject(JSON.toJSONString(data));
            StringBuilder sb = new StringBuilder();
            for (String s : map.keySet()) {
                sb.append(s).append("=").append(map.get(s)).append("&");
            }
            String str = sb.substring(0, sb.length() - 1).toString();
            HttpHeaders httpHeaders = new HttpHeaders();

            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url   "?"   str, new HttpEntity<>(str, httpHeaders), String.class);
            System.out.println("远程调用返回:"  responseEntity.getStatusCode());
            System.out.println("远程调用返回:"  responseEntity.getBody());


        }catch (Exception e) {
            e.printStackTrace();
        }


##方式3
public static <T> T doPostRenYun(String url, Object param, Class<T> responseClass) {
        Map<String, Object> map = JSONObject.parseObject(JSON.toJSONString(param));
        StringBuilder sb = new StringBuilder();
        for (String s : map.keySet()) {
            sb.append(s).append("=").append(map.get(s)).append("&");
        }
        String str = sb.substring(0, sb.length() - 1).toString();
        logger.info("doPostRenYun,url:{},param:{}", url, str);
        HttpHeaders httpHeaders = new HttpHeaders();
        try {
            ResponseEntity<String> responseEntity = RestTemplateConfig.getRestTemplate().postForEntity(url   "?"   str, new HttpEntity<>(str, httpHeaders), String.class);
            T t = JSON.parseObject(responseEntity.getBody(), responseClass);
            logger.info("doPostRenYun,url:{},result:{}", url, JSON.toJSONString(t));
            return t;
        } catch (Exception e) {
            logger.error("doPostRenYun,url:{},error:", url, e);

            return null;
        }
    }

    

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;


/**
 * @Description: restTemplate 配置
 */
public class RestTemplateConfig {
    private static RestTemplate restTemplate;

    static {
        // 长链接保持时间长度20秒
        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager =
                new PoolingHttpClientConnectionManager(20, TimeUnit.SECONDS);
        // 设置最大链接数
        poolingHttpClientConnectionManager.setMaxTotal(2*getMaxCpuCore()   3 );
        // 单路由的并发数
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(2*getMaxCpuCore());

        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);

        // 重试次数3次,并开启
        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3,true));
        HttpClient httpClient = httpClientBuilder.build();
        // 保持长链接配置,keep-alive
        httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

        HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

        // 链接超时配置 10秒
        httpComponentsClientHttpRequestFactory.setConnectTimeout(10000);
        // 连接读取超时配置
        //httpComponentsClientHttpRequestFactory.setReadTimeout(10000);
        // 连接池不够用时候等待时间长度设置,分词那边 500毫秒 ,我们这边设置成1秒
        httpComponentsClientHttpRequestFactory.setConnectionRequestTimeout(3000);

        // 缓冲请求数据,POST大量数据,可以设定为true 我们这边机器比较内存较大
        //httpComponentsClientHttpRequestFactory.setBufferRequestBody(true);

        restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(httpComponentsClientHttpRequestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
    }

    public static RestTemplate getRestTemplate(){
        return restTemplate;
    }

    private static int getMaxCpuCore(){
        int cpuCore = Runtime.getRuntime().availableProcessors();
        return  cpuCore;
    }
}

0 人点赞