RestTemplate使用详解

别再只会用box-shadow加个模糊了!这5个CSS3阴影实战技巧,让你的页面质感瞬间提升 本文深入探讨CSS3的box-shadow属性,揭示5个提升页面质感的实战技巧,包括霓虹灯效、弥散阴影、内阴影应用、动态阴影和组合技法。通过详细代码示例和设计逻辑,帮助开发者突破基础用法,实现更高级的视觉层次和交互效果,特别适合追求细节完美的UI设计师和前端开发者。 阅读详情

在开发中有时候经常需要一些Http请求,请求数据,下载内容,也有一些简单的分布式应用直接使用Http请求作为跨应用的交互协议。

在Java中有不同的Http请求方式,主要就是HttpURLConnection或者ApacheHttpClient,但是这两个用起来都感觉有那么一点点的复杂;

好在Spring内置了RestTemplate作为Http请求的工具类,简化了很多操作,虽然Spring5推出了WebClient,但是整体感觉还是RestTemplate用起来更简单方便一些。

这里记录分享下RestTemplate的常见使用方式,RestTemplate作为Java中最简单好用的Http请求工具类一定要了解一下

常见用法

简单Get\Post请求

    @Test
    public void testGetPost(){
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
        String res = restTemplate.postForObject("http://test.aihe.space/", null, String.class);
        System.out.println(res);
        String res2 = restTemplate.getForObject("http://test.aihe.space/",  String.class);
        System.out.println(res2);
    }

Post提交常规表单

    @Test
    public void testPostFrom(){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        map.add("id", "1");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

        String fooResourceUrl = "http://test.aihe.space/";
        ResponseEntity<String> response = restTemplate.postForEntity(fooResourceUrl, request, String.class);
        System.out.println(response.getStatusCode());
        System.out.println(response.getBody());
    }

Post上传文件

注意:上传文件时的value为FileSystemResource

@Test
    public void testPostFile(){

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> map= new LinkedMultiValueMap<>();
        map.add("id", "1");
        map.add("file",new FileSystemResource("/Users/aihe/code/init/src/test/java/me/aihe/RestTemplateTest.java"));
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
        String fooResourceUrl = "http://test.aihe.space/";
        ResponseEntity<String> response = restTemplate.postForEntity(fooResourceUrl, request, String.class);
        System.out.println(response.getStatusCode());
        System.out.println(response.getBody());
    }

配置项

请求添加Cookie\Header

@Test
    public void testCookieHeader(){

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> map= new LinkedMultiValueMap<>();

        // 常见的Header都可以直接设置
//        headers.set
        headers.set("custom1","customValue1");

        // 设置Cookie
        headers.set(HttpHeaders.COOKIE,"xxxx");

        map.add("id", "1");
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
        String fooResourceUrl = "http://test.aihe.space/";
        ResponseEntity<String> response = restTemplate.postForEntity(fooResourceUrl, request, String.class);
        System.out.println(response.getStatusCode());
        System.out.println(response.getBody());
    }

配置请求工厂 超时、代理

使用Rest请求的时候注意设置超时时间

@Test
    public void testHttpFactory(){
        RestTemplate restTemplate = new RestTemplate();
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(5000);
        requestFactory.setConnectTimeout(3000);

        Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 7890));

        requestFactory.setProxy(proxy);
        restTemplate.setRequestFactory(requestFactory);

        restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
        String res = restTemplate.postForObject("http://test.aihe.space/", null, String.class);
        System.out.println(res);
    }

配置拦截器、转换器,错误处理

@Test
    public void testConverterInterceptor(){
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(Collections.singletonList(new BasicAuthenticationInterceptor("admin","admin")));
        restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        String res = restTemplate.postForObject("http://test.aihe.space/", null, String.class);
        System.out.println(res);
    }

错误重试(额外)

可以考虑使用Spring Retry,但是相当于引入了新的东西,如果没有特殊必要,可以自己简单用for循环做下;

  // Spring Retry方式
  @Bean
  public RetryTemplate retryTemplate() {

    int maxAttempt = Integer.parseInt(env.getProperty("maxAttempt"));
    int retryTimeInterval = Integer.parseInt(env.getProperty("retryTimeInterval"));

    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(maxAttempt);

    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
      // 失败的间隔
    backOffPolicy.setBackOffPeriod(retryTimeInterval); 

    RetryTemplate template = new RetryTemplate();
    template.setRetryPolicy(retryPolicy);
    template.setBackOffPolicy(backOffPolicy);

    return template;
  }

SSL请求

参考:stackoverflow.com/questions/1…

@Test
    public void testSSL() throws FileNotFoundException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
        String keyStorePassword = "123456";
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(new FileInputStream(new File("keyStoreFile")),
                keyStorePassword.toCharArray());

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
                new SSLContextBuilder()
                        .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                        .loadKeyMaterial(keyStore, keyStorePassword.toCharArray())
                        .build(),
                NoopHostnameVerifier.INSTANCE);

        HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(
                socketFactory).build();

        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
                httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String res = restTemplate.postForObject("http://test.aihe.space/", null, String.class);
        System.out.println(res);
    }

基于RestTemplate一些工具

钉钉机器人通知

可以支持发送普通文本、ActionCard,Markdown的消息

import java.util.ArrayList;
import java.util.List;

import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * 使用场景:
 * 功能描述:https://developers.dingtalk.com/document/app/custom-robot-access/title-72m-8ag-pqw
 */
@Slf4j
public class RobotUtils {

    private static RestTemplate restTemplate = new RestTemplate();

    private static String URL = "";

    public static void main(String[] args) {
        sendMarkDownMsg(
            URL,
            "测试",
            "测试",
            new ArrayList<>()
        );
    }

    /**
     * {
     * "msgtype": "text",
     * "text": {
     * "content": "我就是我, @150XXXXXXXX 是不一样的烟火"
     * },
     * "at": {
     * "atMobiles": [
     * "150XXXXXXXX"
     * ],
     * "isAtAll": false
     * }
     * }
     */
    public static void sendTextMsg(String url, String content, List<String> atPerson) {
        RobotMsg robotMsg = new RobotMsg();
        robotMsg.setMsgtype("text");

        RobotAt robotAt = new RobotAt();
        robotAt.setAtAll(false);
        if (atPerson != null && atPerson.size() > 0) {
            robotAt.setAtMobiles(atPerson);
        }
        robotMsg.setAt(robotAt);

        RobotText robotText = new RobotText();
        robotText.setContent(content);

        robotMsg.setText(robotText);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, robotMsg, String.class);
        log.info("sendTextMsg {}",responseEntity.getBody());
    }

    /**
     * @param url            机器人地址
     * @param title          actionCard标题
     * @param text           缩略内容
     * @param vertical 按钮方向
     * @param btns           按钮内容
     */
    public static void sendActionCardMsg(String url, String title, String text, Boolean vertical, List<RobotBtn> btns) {
        RobotMsg robotMsg = new RobotMsg();
        robotMsg.setMsgtype("actionCard");

        RobotAt robotAt = new RobotAt();
        robotAt.setAtAll(false);

        RobotActionCard robotActionCard
            = new RobotActionCard();
        robotActionCard.setTitle(title);
        robotActionCard.setText(text);
        robotActionCard.setBtnOrientation((vertical == null || vertical) ? "0" : "1");
        robotActionCard.setBtns(btns);

        robotMsg.setActionCard(robotActionCard);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, robotMsg, String.class);
        System.out.println(responseEntity.getBody());
    }

    public static void sendMarkDownMsg(String url,String title,String text,List<String> atPerson){
        RobotMarkDownMsg markDownMsg = new RobotMarkDownMsg();
        markDownMsg.setMsgtype("markdown");

        RobotAt robotAt = new RobotAt();
        robotAt.setAtAll(false);
        if (atPerson != null && atPerson.size() > 0) {
            robotAt.setAtMobiles(atPerson);
        }
        markDownMsg.setAt(robotAt);

        RobotMarkdownText markdownText = new RobotMarkdownText();
        markdownText.setTitle(title);
        markdownText.setText(text);
        markDownMsg.setMarkdown(markdownText);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, markDownMsg, String.class);
        System.out.println(responseEntity.getBody());
    }

    public enum SupportRobotEnum {
        /**
         * 测试机器人群
         */
        CESHI("测试机器人群",
            "");

        @Getter
        private String desc;

        @Getter
        private String url;

        SupportRobotEnum(String desc, String url) {
            this.desc = desc;
            this.url = url;
        }
    }

    @Data
    public static class RobotAt {

        public List<String> atMobiles;
        public boolean isAtAll;

    }

    @Data
    public static class RobotMarkDownMsg{
        public String msgtype;

        public RobotAt at;

        public RobotMarkdownText markdown;
    }

    @Data
    public static class RobotMarkdownText {
        String title;
        String text;
    }

    @Data
    public static class RobotMsg {

        public String msgtype;

        public RobotAt at;

        /**
         * 普通文字消息类型消息
         */
        public RobotText text;

        /**
         * actionCard类型消息时支持
         */
        public RobotActionCard actionCard;

    }

    @Data
    public static class RobotText {
        public String content;

    }

    @Data
    public static class RobotActionCard {

        public String title;
        public String text;
        public String hideAvatar;
        public String btnOrientation;
        public List<RobotBtn> btns;

    }

    @Data
    public static class RobotBtn {

        public String title;
        public String actionURL;

        public static RobotBtn buildBtn(String title, String actionUrl) {
            RobotBtn robotBtn = new RobotBtn();
            robotBtn.setActionURL(actionUrl);
            robotBtn.setTitle(title);
            return robotBtn;
        }
    }
}

总结

1、 Http请求在开发过程中也是一个常见的高频操作;

2、Spring封装了Http的工具类RestTemplate非常好用,基本上满足了所有Http相关的需求。

3、这里介绍整理了下RestTemplate的常见使用方式,遇到有对应的内容,直接翻阅使用即可。

RestTemplate 出现401错误 以下面post请求为栗子 使用RestTemplate 请求需要TOKEN认证的接口: //请求参数 MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>(); requestBody.add("param1","dsdd"); requestBody.add("param2","34... 阅读详情

相关推荐

Cesium体渲染实战:从医学CT到气象数据的3D可视化全攻略

本文详细介绍了如何利用Cesium体渲染技术实现医学CT和气象数据的3D可视化。从数据预处理到交互式渲染,涵盖了DICOM和NetCDF格式的处理技巧,以及性能优化的实战策略,帮助开发者高效处理复杂的三维数据集。

weixin_28717431的博客 428

Spring之RestTemplate详解

文章目录1 RestTemplate1.1 引言1.2 环境配置1.2.1 非Spring环境下使用RestTemplate1.2.2 Spring 环境下使用 RestTemplate1.3 API 实践1.3.1 GET请求1.3.1.1 不带参请求1.3.1.2 带参的get请求(使用占位符号传参)1.3.1.3 带参的get请求(restful风格)1.3.1.4 getForEntity使用示例1.3.2 POST请求1.3.2.1 模拟表单请求1.3.2.2 模拟表单请求(传递对象)1.3.2.

上善若泪 3万+

历年北京理工大学复试专业综合题

。

A place to record sth. 2万+

RestTemplate详解

现如今的 IT 项目,由服务端向外发起网络请求的场景,基本上处处可见!传统情况下,在服务端代码里访问 http 服务时,一般会使用 JDK 的 HttpURLConnection 或者 Apache 的 HttpClient,不过这种方法使用起来太过繁琐,而且 api 使用起来非常的复杂,还得操心资源回收。以下载文件为例,通过 Apache 的 HttpClient方式进行下载文件,会很复杂其实Spring已经为我们提供了一种简单便捷的模板类来进行操作,它就是RestTemplate。

qq_62377885的博客 1万+

Python连接StarRocks全流程实践: SQL文件调用与Pandas混合优化

通过这种分阶段混合计算, 既能发挥StarRocks处理海量数据的性能优势, 又能保留Pandas在内存计算中的灵活性, 实现效率与功能的完美平衡.结合SQL的高效聚合与Pandas的灵活计算, 实现查询和数据处理的深度融合.该库基于SQLAlchemy 2.x开发, 仅支持Python 3.x环境.对大批量数据的写入, 建议进行分块. 分块写入较单条插入速度会有显著提升.这样可以避免python代码的查询与SQL耦合, 支持版本化管理.将DDL, DML分离为独立文件, 例如。: 调整连接复用参数。

t.y.Tang的博客 2786

电机控制::软件架构::微型软件架构

所谓软件架构就是软件分层:HAL库,嵌入式操作系统,中间件,应用层。大型项目可参考借鉴ROS/PX4/Apollo/FMT等无人机、机器人、无人驾驶等开源项目;电机控制大型为AUTOSAR架构,小型跑裸机参考 前后台系统 或 微型实时操作系统对模块管理的思想。基本原理还是参照大型项目的架构来的,只是大部分层与块都相对简单,也没有操作系统这一层。硬件架构了解不同芯片组合及其各自的特点。1.FPGA+;2.架构;3.TC387+AUTOSAR架构,车规级,汽车领域常用。

one__leaf的博客 1702

RestTemplate

文章目录RestTemplate简介创建`RestTemplate`方法一添加自定义的拦截器方法二`RestTemplate API`使用GET`getForEntity()``getForObject()`POST`postForEntity()``postForObject()``postForLocation()`使用POST以表单方式提交`HttpHeaders``MultiValueMapRestTemplate 简介 RestTemplate是由Spring框架提供的一个可用于应用中调用re

D1842501760的博客 4万+

32GB Jetson Orin SOM 不能刷机问题排查

拿到了一个新的Orin SOM,当用orin Devkit CVB或定制的CVB不能用Linux_For_Tegra刷机,flash日志(JetPack5.0DP和5.0.1DP都失败了) 2. 确认mb2配置中将CVB的eeprom读取大小设置是否为0 ? 已经确认是正常的 在定制的orin cvb flash上使用Orin devkit som,启动是成功的。但新得到的Orin som并不工作可以排除理由:使用Orin Devkit CVB和Orin SOM(不是Devkit SOM)仍然不能

jzwjzw19900922的博客 1499

RestTemplate使用指南

首先,要对restTemplate进行配置: @Configuration public class Config { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } 具体使用: @Autowired private RestTemplate restTemplate; @Test...

千里之行,始于足下 8980

SIMULINK开发项目实例 1000 例专栏之第802例--基于电机驱动系统的场景实例:永磁同步电机(PMSM)在电动汽车中的矢量控制仿真

随着全球对环境保护的关注增加,电动汽车(Electric Vehicle, EV)因其环保特性而受到广泛关注。永磁同步电机(Permanent Magnet Synchronous Motor, PMSM)由于其高效率、高功率密度和良好的动态响应性能,在电动汽车驱动系统中得到了广泛应用。矢量控制(Field-Oriented Control, FOC)是实现PMSM高性能控制的关键技术之一,它能够实现对电机转矩和磁场的独立控制,从而达到类似直流电机的控制效果。本文将详细介绍如何使用来构建一个。

xiaoheshang_123的博客 270

36、基于启发式的双向RRT*路径规划算法解析

本文介绍了一种基于启发式的双向RRT*路径规划算法(LGHB-RRT*),通过地图预处理、通道区域提取和通道识别点定义,结合随机树的引导生长与可变密度采样机制,显著提升了在复杂通道环境下的搜索效率与成功率。算法采用双向扩展结构,并引入启发式生长策略引导树向通道关键点发展,同时利用路径优化简化最终路径。仿真结果表明,该算法在多种复杂地图中均能高效找到最优路径,优于传统RRT*和Bi-RRT*算法,具备良好的适应性与应用前景。

rgv234567的博客 125

重学SpringBoot3-RestTemplate配置与使用详解

RestTemplate 是 Spring 框架提供的一个用于发送 HTTP 请求的同步客户端工具类。在 SpringBoot 3.x 版本中,我们依然可以使用 RestTemplate 来进行 REST API 的调用。本文将详细介绍如何在 SpringBoot 3 项目中配置和使用 RestTemplate。

CoderJia的学习之路 7787

MinerU 系列教程 | 第二课:快速上手 -- 安装与第一次解析

本篇教程作为的第二课,将带你从零完成 MinerU 的环境搭建、模型下载,并成功运行第一次文档解析。上一课我们从宏观视角认识了 MinerU,本课开始正式动手实践。

weixin_43674738的博客 313

resttemplate 设置请求头_RestTemplate的使用

技术之路,不进即退 。吾等菜鸡应埋头于技术之路,破甲斩棘。勿做土鸡瓦狗,贪图安逸。今天我就来讲一讲我对于RestTemplate的一些理解,我相信大家肯定很多都会用。我今天把它拿出来讲的原因,就是让不清楚的人通过阅读这篇文章能够直接会用并且能懂得其中大概的原理。其实去年大学毕业到现在我可以说用过这个东西很多次了,由于网上的资料繁杂,所以当时只是单纯想着会用就行,具体的一些琐碎知识并未深究。一 :概...

weixin_39887925的博客 3038

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

RestTemplate 用法详解

上篇文章带大家学习了一下基本的微服务环境搭建,由 provider 提供服务, consumer 通过 DiscoveryClient 先去 eureka 上获取 provider 的服务的地址,获取到地址之后再去调用相关的服务。在服务的调用过程中,使用到了一个工具,叫做 RestTemplate,RestTemplate 是由 Spring 提供的一个 HTTP 请求工具。在上文的案例中,开发者...

Lzc的博客 25万+

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

RestTemplate关于https的使用详解

RestTemplate关于https的使用详解

無言的博客 1664

restTemplate的使用

restTemplate的使用

m0_72167535的博客 1万+

RestTemplate教程

getForObject 方法和 getForEntity 方法类似,getForObject 方法也有三个重载的方法,参数和 getForEntity 一样,因此这里我就不重复介绍参数了,这里主要说下 getForObject 和 getForEntity 的差异,这两个的差异主要体现在返回值的差异上, getForObject 的返回值就是服务提供者返回的数据,使用 getForObject 无法获取到响应头。我们发现带参数的get请求需要将参数拼接到url中,参数少好说,参数多了就很麻烦。

qq_29384093的博客 1452

java resttemplate_详解RestTemplate的三种使用方式

什么是RestTemplate传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐。spring提供了一种简单便捷的模板类来进行操作,这就是RestTemplate。准备服务端我是用的是一个普通的API@RestControllerpublic class ServerController {@GetMapping("/msg"...

weixin_39748445的博客 5573

RestTemplate 详解

背景这段时间自己做的项目中需要调用服务提供者的服务(接口),具体就是:我这边需要将页面所输入的 Groovy 脚本代码传给别人提供的服务接口,然后那边返回脚本编译的结果给我,我需要将编译结果展示在页面,用的就是 RestTemplate 了,那 RestTemplate 是什么呢?简单说就是:简化了发起 HTTP 请求以及...

Salted fish in hand, I have the world. 854

详解 RestTemplate 操作

详解 RestTemplate 操作作为开发人员,我们经常关注于构建伟大的软件来解决业务问题。数据只是软件完成工作时 要处理的原材料。但是如果你问一下业务人员,数据和软件谁更重要的话,他们很可能会选择 数据。数据是许多业务的生命之血。软件通常是可以替换的,但是多年积累的数据是永远不能 替换的。近几年来,以信息为中心的表述性状态转移(Representational State Transfer

只有变秃 才能变强 21万+

SpringBoot RestTemplate使用详解

RestTemplate 是 Spring Restful Client 用于调用restful接口 HTTP Restful SpringCloud 微服务 SpringCloud服务调用有两种方式:restTemplate和Fegin RPC-->Dubbo RestTemplate API使用方法 HTTP method RestTemp...

凡事不敷衍,才能被生活所厚待 720
上一篇: hibernate延迟加载(get和load的区别)
下一篇: 《Thinking In Java》作者:不要使用并发!
Java技术那些事儿
博客等级 码龄5年 2306粉丝 2584原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址