springboot(39) : RestTemplate完全体

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

1.使用(注入RestTemplateService)


    @Autowired
    private RestTemplateService restTemplateService;

2.RestTemplate配置类

package com.alibaba.gts.flm.abnormal.recognition.biz.core.config;

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;

/**
 * @Author zanhonglei
 * @DAte 2019/10/12 6:52 下午
 * @Description
 * @Version V1.0
 * @Modify by
 **/
@Configuration
public class RestTemplateConfig {
    /**
     * 超时时间3秒
     */
    private static final int TIME_OUT = 1000 * 30;

    @Bean
    public RestTemplate restTemplate(){
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        // 链接超时1分钟
        requestFactory.setConnectTimeout(TIME_OUT);
        requestFactory.setReadTimeout(TIME_OUT);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        List<HttpMessageConverter<?>> 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依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.14</version>
            <scope>provided</scope>
        </dependency>

需要安装lombok插件  

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.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.math.BigDecimal;
import java.net.URI;
import java.nio.file.Files;
import java.util.Map;

/**
 * @Author: liyue
 * @Date: 2022/08/10/10:14
 * @Description:
 */
@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() + "    req.size:{}" + System.lineSeparator() + "    resp.size:{}" + 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), "-", "-");
            printLog(url, "get", "-", "-", resp, currentTimeMillis);
            return resp;
        } catch (Exception e) {
            log.error("[get]接口调用失败,url:{},error:{}", url, ExceptionUtils.getStackTrace(e));
            return null;
        }
    }

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

    public String postByHeader(String url, JSONObject req, Map<String, String> headerParams) {
        long currentTimeMillis = System.currentTimeMillis();
        // http请求头
        HttpHeaders headers = new HttpHeaders();
        headerParams.forEach((k, v) -> headers.set(k, v));
        // 请求头设置属性
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        String reqs = JSONObject.toJSONString(req);
        HttpEntity<String> request = new HttpEntity<>(reqs, headers);
        ResponseEntity<String> result;
        try {
            result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
            printLog(url, "post", reqs, "-", result.getBody(), currentTimeMillis);
            return result.getBody();
        } catch (Exception e) {
            log.error("[post]接口调用失败,url:{},req:{},error:{}", url, smallStr(reqs), 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<String> request = new HttpEntity<>(reqs, headers);
        ResponseEntity<String> result;
        try {
            result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
            printLog(url, "post", reqs, "-", result.getBody(), currentTimeMillis);
            return result.getBody();
        } catch (Exception e) {
            log.error("[post]接口调用失败,url:{},req:{},error:{}", url, smallStr(reqs), ExceptionUtils.getStackTrace(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<String> request = new HttpEntity<>(req, headers);
        ResponseEntity<String> result;
        try {
            result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
            printLog(url, "postStr", req, "-", result.getBody(), currentTimeMillis);
            return result.getBody();
        } catch (Exception e) {
            log.error("[postStr]接口调用失败,url:{},req:{},error:{}", url, smallStr(req), ExceptionUtils.getStackTrace(e));
            return null;
        }
    }

    public String upload(String url, String filePath) {
        try {
            long currentTimeMillis = System.currentTimeMillis();
            File f = new File(filePath);
            byte[] fileContent = Files.readAllBytes(f.toPath());
            ByteArrayResource resource = new ByteArrayResource(fileContent) {
                @Override
                public String getFilename() {
                    return f.getName();
                }
            };

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", resource);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            RequestEntity<MultiValueMap<String, Object>> requestEntity = new RequestEntity<>(body, headers, HttpMethod.POST, URI.create(url));
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);
            printLog(url, "upload", filePath, "-", responseEntity.getBody(), currentTimeMillis);
            return responseEntity.getBody();
        } catch (Exception e) {
            log.error("[upload]接口调用失败,url:{},filePath:{},error:{}", url, filePath, ExceptionUtils.getStackTrace(e));
            return null;
        }
    }
    // --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    public void printLog(String url, String method, String req, String headers, String resp, Long currentTimeMillis) {
        log.info(LOG_PATTERN, method, url, smallStr(req), headers, smallStr(resp), getHaoShi(currentTimeMillis), getSize(req), getSize(resp));
    }

    public 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 + "毫秒";
    }

    /**
     * 计算大小
     *
     * @param str 字符串
     * @return
     */
    public static String getSize(String str) {
        if (str == null) {
            return "-";
        }
        byte[] bytes = str.getBytes();
        int length = bytes.length;
        double d7 = length / Math.pow(1024.0, 7);
        if (d7 > 1) return round(d7, 1) + "ZB";
        double d6 = length / Math.pow(1024.0, 6);
        if (d6 > 1) return round(d6, 1) + "EB";
        double d5 = length / Math.pow(1024.0, 5);
        if (d5 > 1) return round(d5, 1) + "PB";
        double d4 = length / Math.pow(1024.0, 4);
        if (d4 > 1) return round(d4, 1) + "TB";
        double d3 = length / Math.pow(1024.0, 3);
        if (d3 > 1) return round(d3, 1) + "GB";
        double d2 = length / Math.pow(1024.0, 2);
        if (d2 > 1) return round(d2, 1) + "MB";
        double d1 = length / Math.pow(1024.0, 1);
        ;
        if (d1 > 1) return round(d1, 1) + "KB";
        return length + "B";
    }

    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;
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值