Java便携开发,调用第三方接口工具封装,可直接复制粘贴使用

引语

在Java开发中,我们需要应用第三方服务,spring-boot框架其实已经封装了一个调用工具,但是调用十分生硬,让代码灵活起来,以下分享是一个工具类,针对调用第三方服务,这样可以免去你再去写 feign,open-feign 或者其他 HttpConnection 之类的原始代码,因为看似很简化,实际emmm,不评论。

先分享工具类,感兴趣的大佬可以直接复制粘贴到你的工具类中

package com.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Configuration
public class RestTemplateUtils {

    private static final int DEFAULT_TIMEOUT = 5000;

    private static RestTemplate instanceRestTemplate;

    @Bean("restTemplate")
    public RestTemplate restTemplate() {
        instanceRestTemplate = getInstance();
        return instanceRestTemplate;
    }

    public static RestTemplate getInstance() {
        return getRestTemplateByTimeout(DEFAULT_TIMEOUT);
    }

    public static RestTemplate getRestTemplateByTimeout(int timeout) {
        return getRestTemplateByTimeout(timeout, timeout);
    }

    public static RestTemplate getRestTemplateByTimeout(int connectTimeout, int readTimeout) {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(connectTimeout);
        httpRequestFactory.setConnectTimeout(connectTimeout);
        httpRequestFactory.setReadTimeout(readTimeout);
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);

        List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
        httpMessageConverters.forEach(httpMessageConverter -> {
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                StringHttpMessageConverter messageConverter = (StringHttpMessageConverter)httpMessageConverter;
                messageConverter.setDefaultCharset(StandardCharsets.UTF_8);
            }
        });

        restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(new LoggingRequestInterceptor());
        restTemplate.setInterceptors(interceptors);
        return restTemplate;
    }

    /**
     * 无参数方式post
     *
     * @param restTemplate
     * @param url
     * @param clazz
     * @param 
     * @return
     */
    public static <T> T post(RestTemplate restTemplate, String url, Class<T> clazz) {
        return post(restTemplate, url, null, null, null, clazz);
    }

    /**
     * 只有query参数方式post
     *
     * @param restTemplate
     * @param url
     * @param queryParamMap
     * @param clazz
     * @param 
     * @return
     */
    public static <T> T post(RestTemplate restTemplate, String url, LinkedMultiValueMap<String, String> queryParamMap, Class<T> clazz) {
        return post(restTemplate, url, null, queryParamMap, null, clazz);
    }

    /**
     * body参数方式post
     *
     * @param restTemplate
     * @param url
     * @param body
     * @param clazz
     * @param 
     * @return
     */
    public static <T> T post(RestTemplate restTemplate, String url, Object body, Class<T> clazz) {
        return post(restTemplate, url, body, null, null, clazz);
    }

    /**
     * body header参数方式post
     *
     * @param restTemplate
     * @param url
     * @param body
     * @param httpHeaders
     * @param clazz
     * @param 
     * @return
     */
    public static <T> T post(RestTemplate restTemplate, String url, Object body, HttpHeaders httpHeaders, Class<T> clazz) {
        return post(restTemplate, url, body, null, httpHeaders, clazz);
    }

    /**
     * 文件方式
     *
     * @param restTemplate
     * @param url
     * @param map
     * @param clazz
     * @param 
     * @return
     */
    public static <T> T postFile(RestTemplate restTemplate, String url, LinkedMultiValueMap<String, Object> map, Class<T> clazz) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        return postFile(restTemplate, url, map, headers, clazz);
    }

    /**
     * 可带query参数
     *
     * @param restTemplate
     * @param url
     * @param body
     * @param queryParamMap query参数
     * @param headers
     * @param clazz
     * @param 
     * @return
     * @param 
     */
    public static <T, E> T post(RestTemplate restTemplate, String url, E body, LinkedMultiValueMap<String, String> queryParamMap, HttpHeaders headers, Class<T> clazz) {
        String requestUrl = url;
        if (MapUtils.isNotEmpty(queryParamMap)) {
            requestUrl = UriComponentsBuilder.fromUriString(url).queryParams(queryParamMap).build().encode(StandardCharsets.UTF_8).toUriString();
        }
        if (null == headers) {
            headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        }
        HttpEntity<E> entity = new HttpEntity<>(body, headers);
        ResponseEntity<T> exchange = exchangePost(restTemplate, requestUrl, entity, clazz);
        return exchange.getBody();
    }

    /**
     * 文件方式FileSystemResource
     *
     * @param restTemplate
     * @param url
     * @param map
     * @param headers
     * @param clazz
     * @param 
     * @return
     */
    public static <T> T postFile(RestTemplate restTemplate, String url, LinkedMultiValueMap<String, Object> map, HttpHeaders headers, Class<T> clazz) {
        if (null == headers) {
            headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        }
        HttpEntity<LinkedMultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);
        ResponseEntity<T> exchange = exchangePost(restTemplate, url, entity, clazz);
        return exchange.getBody();
    }

    private static <E, T> ResponseEntity<T> exchangePost(RestTemplate restTemplate, String requestUrl, HttpEntity<E> entity, Class<T> targetClazz) {
        RestTemplate restTemplate$;
        if (null == restTemplate) {
            restTemplate$ = instanceRestTemplate;
        } else {
            restTemplate$ = restTemplate;
        }
        return restTemplate$.exchange(requestUrl, HttpMethod.POST, entity, targetClazz);
    }

}


这里的注解都是在spring-boot项目下自带的,所以需要你Alt + Enter,Import class即可,日志注解的话,根据项目规定添加就行。这里缺少2个类,一个是RestTemplateResponseErrorHandler,LoggingRequestInterceptor。继续添加:

@Slf4j
public class RestTemplateResponseErrorHandler extends DefaultResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        return false;
    }

}

第二个类:

@Slf4j
public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        traceRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        traceResponse(response);
        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) {
        if (log.isDebugEnabled()) {
            log.debug("===========================request begin================================================");
            log.debug("URI         : {}", request.getURI());
            log.debug("Method      : {}", request.getMethod());
            log.debug("Headers     : {}", request.getHeaders());
            log.debug("Request body: {}", new String(body, StandardCharsets.UTF_8));
            log.debug("==========================request end================================================");
        }
    }

    private void traceResponse(ClientHttpResponse response) throws IOException {
        if (log.isDebugEnabled()) {
            StringBuilder inputStringBuilder = new StringBuilder();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), StandardCharsets.UTF_8));
            String line = bufferedReader.readLine();
            while (line != null) {
                inputStringBuilder.append(line);
                inputStringBuilder.append('\n');
                line = bufferedReader.readLine();
            }
            log.debug("============================response begin==========================================");
            log.debug("Status code  : {}", response.getStatusCode());
            log.debug("Status text  : {}", response.getStatusText());
            log.debug("Headers      : {}", response.getHeaders());
            log.debug("Response body: {}", inputStringBuilder);
            log.debug("=======================response end=================================================");
        }

    }

}

当你添加完成,这个工具就可以任你使用了,首先你的代码非常的简洁,其次还是先举例子吧

String url = "www.baidu.com";
String thirdResult = RestTemplateUtils.post(null, url , dto, String.class);

这里解说一下,第一个参数传null即可,第二个是第三方链接,无论你丢在配置文件或者丢在程序中都行,第三个就是body参数,第四呢就是返回的结果。

建议都用String,因为够万能,而且巨方便。

其他使用方式,若用到了有不理解的可以留言,我会不定期回复。但是很多情况下,我更希望大家多多尝试,当然也希望各位大佬不吝赐教。

你可能感兴趣的:(java,开发语言)