springboot(39) : RestTemplate完全体

        HTTP请求调用集成,支持GET,POST,JSON,Header调用,日志打印,请求耗时计算,设置中文编码

1.使用(注入RestTemplateService)


    @Autowired
    private RestTemplateService restTemplateService;

2.RestTemplate配置类


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;

@Configuration
public class RestTemplateConfig {
    /**
     * 超时时间3秒
     */
    private static final int TIME_OUT = 1000 * 3;

    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        // 链接超时设置
        requestFactory.setConnectTimeout(TIME_OUT);
        requestFactory.setReadTimeout(TIME_OUT);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        List> httpMessageConverters = restTemplate.getMessageConverters();
        httpMessageConverters.stream().forEach(httpMessageConverter -> {
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                StringHttpMessageConverter messageConverter = (StringHttpMessageConverter) httpMessageConverter;
                messageConverter.setDefaultCharset(Charset.forName("UTF-8"));
            }
        });
        return restTemplate;
    }
}

3.maven依赖

        
            com.alibaba
            fastjson
            1.2.83
        
        
            org.apache.commons
            commons-lang3
            3.9
        
        
            org.projectlombok
            lombok
            1.18.14
            provided
        

4.RestTemplateService


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Map;


@Service
@Slf4j
public class RestTemplateService {

    @Autowired
    private RestTemplate restTemplate;

    private static final String LOG_PATTERN = System.lineSeparator()
            + "    method:{}" + System.lineSeparator()
            + "    url:{}" + System.lineSeparator()
            + "    req:{}" + System.lineSeparator()
            + "    header:{}" + System.lineSeparator()
            + "    resp:{}" + System.lineSeparator()
            + "    time:{}" + System.lineSeparator();

    public String get(String url) {
        long currentTimeMillis = System.currentTimeMillis();
        try {
            String resp = restTemplate.getForObject(url, String.class);
            log.info(LOG_PATTERN, "get", url, "-", "-", smallStr(resp), getHaoShi(currentTimeMillis));
            return resp;
        } catch (Exception e) {
            log.error("接口调用失败,url:{}", url, ExceptionUtils.getStackTrace(e));
            return null;
        }
    }

    public String getHeader(String url, Map headerParms) {
        long currentTimeMillis = System.currentTimeMillis();
        HttpHeaders headers = new HttpHeaders();
        headerParms.forEach((k, v) -> headers.set(k, v));
        HttpEntity request = new HttpEntity<>(headers);
        try {
            String resp = restTemplate.exchange(url, HttpMethod.GET, request, String.class).getBody();
            log.info(LOG_PATTERN, "getHeader", url, "-", JSONObject.toJSONString(headerParms), smallStr(resp), getHaoShi(currentTimeMillis));
            return resp;
        } catch (Exception e) {
            log.error("接口调用失败,url:{},headerParms:{}", url, JSONObject.toJSONString(headerParms), ExceptionUtils.getStackTrace(e));
            return null;
        }
    }

    public String post(String url, JSONObject req) {
        long currentTimeMillis = System.currentTimeMillis();
        // http请求头
        HttpHeaders headers = new HttpHeaders();
        // 请求头设置属性
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        String reqs = JSONObject.toJSONString(req);
        HttpEntity request = new HttpEntity<>(reqs, headers);
        ResponseEntity result;
        try {
            result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
            log.info(LOG_PATTERN, "post", url, reqs, "-", smallStr(result.getBody()), getHaoShi(currentTimeMillis));
            return result.getBody();
        } catch (Exception e) {
            log.error("接口调用失败,url:{},req:{}", url, reqs.length() < 10000 ? reqs : "", e);
            return null;
        }
    }

    public String postStr(String url, String req) {
        long currentTimeMillis = System.currentTimeMillis();
        // http请求头
        HttpHeaders headers = new HttpHeaders();
        // 请求头设置属性
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity request = new HttpEntity<>(req, headers);
        ResponseEntity result;
        try {
            result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
            log.info(LOG_PATTERN, "postStr", url, req, "-", smallStr(result.getBody()), getHaoShi(currentTimeMillis));
            return result.getBody();
        } catch (Exception e) {
            log.error("接口调用失败,url:{},req:{}", url, smallStr(req), e);
            return null;
        }
    }

    public static String smallStr(String str) {
        if (str == null) {
            return null;
        }
        boolean tooLong = str.length() > 1000;
        return tooLong ? str.substring(0, 1000) + " ..." : str;
    }

    /**
     * 计算耗时
     *
     * @param time 开始时间戳(毫秒)
     * @return
     */
    public static String getHaoShi(Long time) {
        long t = System.currentTimeMillis() - time;
        double d7 = t / 1000.0 / 60 / 60 / 24 / 30 / 12 / 100;
        if (d7 > 1)
            return round(d7, 1) + "纪元";
        double d6 = t / 1000.0 / 60 / 60 / 24 / 30 / 12;
        if (d6 > 1)
            return round(d6, 1) + "年";
        double d5 = t / 1000.0 / 60 / 60 / 24 / 30;
        if (d5 > 1)
            return round(d5, 1) + "月";
        double d4 = t / 1000.0 / 60 / 60 / 24;
        if (d4 > 1)
            return round(d4, 1) + "天";
        double d3 = t / 1000.0 / 60 / 60;
        if (d3 > 1)
            return round(d3, 1) + "小时";
        double d2 = t / 1000.0 / 60;
        if (d2 > 1)
            return round(d2, 1) + "分钟";
        double d1 = t / 1000.0;
        if (d1 > 1)
            return round(d1, 1) + "秒";
        return t + "毫秒";
    }

    public static Double round(Double data, int amount) {
        if (data == null) {
            return null;
        } else {
            double result = (new BigDecimal(data)).setScale(amount, 4).doubleValue();
            return result;
        }
    }
}

你可能感兴趣的:(#,springboot,spring,boot,后端,java,RestTemplate,RestTemplate集成)