当前位置: 首页 > news >正文

springboot(39) : RestTemplate完全体

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

1.使用(注入RestTemplateService)

@Autowiredprivate 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;@Beanpublic RestTemplate restTemplate() {SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();// 链接超时设置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>

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 {@Autowiredprivate 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<String, String> headerParms) {long currentTimeMillis = System.currentTimeMillis();HttpHeaders headers = new HttpHeaders();headerParms.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();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<String> request = new HttpEntity<>(reqs, headers);ResponseEntity<String> 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<String> request = new HttpEntity<>(req, headers);ResponseEntity<String> 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;}}
}

http://www.lryc.cn/news/110870.html

相关文章:

  • python中计算2的32次方减1,python怎么算2的3次方
  • 阿里云SLB负载均衡ALB、CLB和NLB有什么区别?
  • SynergyNet(头部姿态估计 Head Pose Estimation)复现 demo测试
  • mysql高级(尚硅谷-夏磊)
  • C++实用技术(二)std::function和bind绑定器
  • vue框架 element导航菜单el-submenu 简单使用方法--以侧边栏举例
  • Nodejs 第八章(npm搭建私服)
  • React Native获取手机屏幕宽高(Dimensions)
  • kubernetes基于helm部署gitlab
  • jmeter 5.1彻底解决中文上传乱码
  • 云运维工具
  • 【RL】Wasserstein距离-GAN背后的直觉
  • sentinel引入CommonFilter类
  • Phoenix创建local index失败
  • css3 hover border 流动效果
  • jdk安装
  • utf8mb4_general_ci 和utf8mb4_unicode_ci有什么异同,有什么优劣
  • java实现钉钉群机器人@机器人获取信息后,机器人回复(机器人接收消息)
  • ffmpeg转码时出现missing picture in access unit with size 14019
  • 以Llama-2为例,在生成模型中使用自定义StoppingCriteria
  • servlet接受参数和乱码问题
  • 2023-08-05力扣今日三题
  • webpack图片压缩
  • JPA使用nativeQuery自定义SQL怎么插入一个对象参数呢?
  • 用C语言构建一个数字识别卷积神经网络
  • 【CSS】圆形放大的hover效果
  • work weekly
  • Mac端口扫描工具
  • 如何隐藏开源流媒体EasyPlayer.js视频H.265播放器的实时录像按钮?
  • Spring Cloud Eureka 和 zookeeper 的区别