【Java】RestTemplateUtils(RestTemplate 工具类)

RestTemplateUtils

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.ParameterizedType;
import java.util.Objects;

public class RestTemplateUtils {

    private static final int CONNECT_TIMEOUT = 8000;
    private static final int SOCKET_TIMEOUT  = 8000;

    private static RestTemplate getCustomRestTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(CONNECT_TIMEOUT);
        factory.setReadTimeout(SOCKET_TIMEOUT);
        return new RestTemplate(factory);
    }

    public static <T> T fetch(String url,
                              String method,
                              HttpEntity<?> requestEntity,
                              ParameterizedType parameterizedType) {
        ParameterizedTypeReference<T> responseType = ParameterizedTypeReference.forType(parameterizedType);
        return fetch(url, method, requestEntity, responseType);
    }

    public static <T> T fetch(String url,
                              String method,
                              Object body,
                              HttpHeaders headers,
                              ParameterizedType parameterizedType) {
        HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
        return fetch(url, method, requestEntity, parameterizedType);
    }

    public static <T> T fetch(String url,
                              String method,
                              HttpEntity<?> requestEntity,
                              ParameterizedTypeReference<T> responseType) {
        T ret = null;
        RestTemplate restTemplate = getCustomRestTemplate();
        HttpMethod httpMethod = HttpMethod.resolve(Objects.nonNull(method) ? method.toUpperCase() : "");
        if (Objects.nonNull(httpMethod)) {
            ResponseEntity<T> responseEntity = restTemplate.exchange(url, httpMethod, requestEntity, responseType);
            ret = responseEntity.getBody();
        }
        return ret;
    }

    public static <T> T fetch(String url,
                              String method,
                              Object body,
                              HttpHeaders headers,
                              ParameterizedTypeReference<T> responseType) {
        HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
        return fetch(url, method, requestEntity, responseType);
    }

    public static <T> T fetch(String url,
                              String method,
                              HttpEntity<?> requestEntity,
                              Class<T> clazz) {
        T ret = null;
        RestTemplate restTemplate = getCustomRestTemplate();
        HttpMethod httpMethod = HttpMethod.resolve(Objects.nonNull(method) ? method.toUpperCase() : "");
        if (Objects.nonNull(httpMethod)) {
            ResponseEntity<T> responseEntity = restTemplate.exchange(url, httpMethod, requestEntity, clazz);
            ret = responseEntity.getBody();
        }
        return ret;
    }

    public static <T> T fetch(String url,
                              String method,
                              Object body,
                              HttpHeaders headers,
                              Class<T> clazz) {
        HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
        return fetch(url, method, requestEntity, clazz);
    }

    public static <T> T fetch(String url,
                              String method,
                              RequestCallback callback,
                              ResponseExtractor<T> extractor) {
        T ret = null;
        RestTemplate restTemplate = getCustomRestTemplate();
        HttpMethod httpMethod = HttpMethod.resolve(Objects.nonNull(method) ? method.toUpperCase() : "");
        if (Objects.nonNull(httpMethod)) {
            ret = restTemplate.execute(url, httpMethod, callback, extractor);
        }
        return ret;
    }



    /*
    public static void main(String[] args) {
        // HttpHeaders headers = new HttpHeaders();
        // headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        // MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        // form.add("data", "");
        // form.add("file", new FileSystemResource(""));
        // form.add("byte", new ByteArrayResource(new byte[0], ""));
        // HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(form, headers);
        // fetch("url", "POST", requestEntity, JSONObject.class);
//    */

}

RestTemplateKit

import lombok.SneakyThrows;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustAllStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
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.apache.http.ssl.SSLContexts;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;

public enum RestTemplateKit {

    SCOPE(8000, 8000, 512, 32);

    private final int READ_TIMEOUT;
    private final int CONNECT_TIMEOUT;
    private final int MAX_TOTAL;
    private final int MAX_PER_ROUTE;
    private final ClientHttpRequestFactory factory;
    private final RestTemplate client;

    RestTemplateKit(int readTimeout, int connectTimeout, int maxTotal, int perRoute) {
        READ_TIMEOUT = readTimeout;
        CONNECT_TIMEOUT = connectTimeout;
        MAX_TOTAL = maxTotal;
        MAX_PER_ROUTE = perRoute;
        factory = new HttpComponentsClientHttpRequestFactory(newHttpClient());
        client = new RestTemplate(factory);
    }

    @SneakyThrows
    private CloseableHttpClient newHttpClient() {
        RequestConfig reqCfg = RequestConfig.custom()
                .setSocketTimeout(READ_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT)
                .build();
        SocketConfig sockCfg = SocketConfig.custom()
                .setTcpNoDelay(true)
                .setSoTimeout(READ_TIMEOUT)
                .build();
        SSLContext sslCtx = SSLContexts.custom()
                .loadTrustMaterial(TrustAllStrategy.INSTANCE)
                .build();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", new SSLConnectionSocketFactory(sslCtx, NoopHostnameVerifier.INSTANCE))
                .build();
        PoolingHttpClientConnectionManager manager
                = new PoolingHttpClientConnectionManager(registry);
        manager.setMaxTotal(MAX_TOTAL);
        manager.setDefaultMaxPerRoute(MAX_PER_ROUTE);
        HttpClientBuilder builder = HttpClients.custom();
        builder.setDefaultRequestConfig(reqCfg);
        builder.setDefaultSocketConfig(sockCfg);
        builder.setConnectionManager(manager);
        builder.setRetryHandler(new DefaultHttpRequestRetryHandler(1, true));
        return builder.build();
    }

    public RestTemplate singleton() {
        return client;
    }

    public RestTemplate prototype() {
        return new RestTemplate(factory);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值