springboot(39) : RestTemplate完全体

这篇具有很好参考价值的文章主要介绍了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插件  文章来源地址https://www.toymoban.com/news/detail-632200.html

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

到了这里,关于springboot(39) : RestTemplate完全体的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接

    系列文章: SpringBoot + Vue前后端分离项目实战 || 一:Vue前端设计 SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接 SpringBoot + Vue前后端分离项目实战 || 三:Spring Boot后端与Vue前端连接 SpringBoot + Vue前后端分离项目实战 || 四:用户管理功能实现 SpringBoot + Vue前后

    2024年02月11日
    浏览(50)
  • 微信小程序的授权登录-Java 后端 (Spring boot)

    微信开发文档链接:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html 一个可以测试的微信小程序 此微信小程序的APPID和APPscret(至开发者后台获取) 从时序图我们可以了解到流程大致分为两步: 小程序端获取code后传给Java后台 Java后台获取code后向微信后台接口

    2024年02月09日
    浏览(38)
  • Spring Boot进阶(48):【实战教程】SpringBoot集成WebSocket轻松实现实时消息推送

            WebSocket是一种新型的通信协议,它可以在客户端与服务器端之间实现双向通信,具有低延迟、高效性等特点,适用于实时通信场景。在SpringBoot应用中,集成WebSocket可以方便地实现实时通信功能,如即时聊天、实时数据传输等。         本文将介绍如何在Sprin

    2024年02月09日
    浏览(38)
  • “从零开始学习Spring Boot:快速搭建Java后端开发环境“

    标题:从零开始学习Spring Boot:快速搭建Java后端开发环境 摘要:本文将介绍如何从零开始学习Spring Boot,并详细讲解如何快速搭建Java后端开发环境。通过本文的指导,您将能够快速搭建一个基于Spring Boot的Java后端开发环境并开始编写代码。 正文: 一、准备工作 在开始之前,

    2024年02月15日
    浏览(42)
  • Spring Boot进阶(55):SpringBoot之集成MongoDB及实战使用 | 超级详细,建议收藏

            随着大数据时代的到来,数据存储和处理变得越来越重要。而MongoDB作为一种非关系型数据库,具有高效的数据存储和处理能力,被越来越多地应用于各种领域。尤其在Web应用开发中,SpringBoot框架已经成为了主流选择之一。在这篇文章中,我们将探讨如何将MongoD

    2024年02月17日
    浏览(33)
  • spring boot +springboot集成es7.9.1+canal同步到es

    未经许可,请勿转载。 其实大部分的代码是来源于 参考资料来源 的 主要代码实现 ,我只是在他的基础上增加自定义注解,自定义分词器等。需要看详细源码的可以去看 主要代码实现 ,结合我的来使用。 有人会问为什么需要自定义注解,因为elasticsearch7.6 索引将去除type 没

    2023年04月11日
    浏览(74)
  • Spring Boot进阶(48):SpringBoot之集成WebSocket及使用说明 | 超级详细,建议收藏

            WebSocket是一种新型的通信协议,它可以在客户端与服务器端之间实现双向通信,具有低延迟、高效性等特点,适用于实时通信场景。在SpringBoot应用中,集成WebSocket可以方便地实现实时通信功能,如即时聊天、实时数据传输等。         本文将介绍如何在Sprin

    2024年02月16日
    浏览(40)
  • 【Spring Boot】SpringBoot 2.6.6 集成 SpringDoc 1.6.9 生成swagger接口文档

    之前常用的SpringFox在2020年停止更新了,新项目集成SpringFox出来一堆问题,所以打算使用更活跃的SpringDoc,这里简单介绍一下我这边SpringBoot2.6.6集成SpringDoc1.6.9的demo。 官网链接 maven为例: 代码如下(示例): 默认路径: UI界面 http://localhost:9527/swagger-ui/index.html json界面 http:/

    2024年02月09日
    浏览(29)
  • Spring Boot进阶(49):SpringBoot之集成WebSocket实现前后端通信 | 超级详细,建议收藏

            在上一期,我对WebSocket进行了基础及理论知识普及学习,WebSocket是一种基于TCP协议实现的全双工通信协议,使用它可以实现实时通信,不必担心HTTP协议的短连接问题。Spring Boot作为一款微服务框架,也提供了轻量级的WebSocket集成支持,本文将介绍如何在Spring Boot项

    2024年02月14日
    浏览(29)
  • Spring Boot进阶(68):如何用SpringBoot轻松实现定时任务?集成Quartz来帮你!(附源码)

            Quartz是一个非常流行的开源调度框架,它提供了许多强大的功能,如定时任务调度、作业管理、任务持久化等。而SpringBoot是目前Java开发中非常流行的框架之一,其对各种开源框架集成非常方便。本篇文章将介绍如何在SpringBoot中集成Quartz,以便于更好的管理和调度

    2024年02月07日
    浏览(42)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包