这里写目录标题

  • 前言
  • 准备
    • 引入 lib
    • 创建 RestTemplate Bean
  • 认识一下RestTemplate
  • getForObject 示例
    • 简单调用
    • 参数拼接
  • postForEntity 示例
    • 构造 request Object
    • 在 URL 中传参
  • postForObject 示例
    • 构造 request Object
    • 在 URL 中传参
  • (POST)Content-Type: application/x-www-form-urlencoded
  • (POST)Content-Type: application/json
  • (POST)Content-Type: application/json
  • postForEntity 与 postForObject 的区别

前言

  • spring-boot 2.0.0.RELEASE
  • spring-web 5.0.4.RELEASE
  • maven 3.5.0
  • Eclipse Version: 2019-09 R (4.13.0)
  • 使用 RestTemplate 调用 restful 接口
  • 官方说明在这里和这里

准备

引入 lib

RestTemplate 类的完整路径为 : org.springframework.web.client.RestTemplate 。
RestTemplate 类在 lib : spring-web 中。

springboot项目引入 lib:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>

创建 RestTemplate Bean

@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate getRestTemplate() {return new RestTemplate();}
}

说明:

  • 也可以不创建Bean。不创建Bean时,需要每次new RestTemplate()
  • 如果既不创建Bean,也不每次new RestTemplate(),则会遇到错误No qualifying bean of type 'org.springframework.web.client.RestTemplate'

认识一下RestTemplate

常用方法,getForEntitygetForObject方法、postForEntitypostForObject方法。ForEntity方法和ForObject方法的差别在于返回值。ResponseEntity类型的返回值可以获取到完整的Response信息,比如header、http status。部分相关方法定义:

  • public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException
  • public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException
  • public <T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException
  • public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException

exchange方法更偏向于自己处理RequestEntity的情况。

getForObject 示例

简单调用

String url = "https://www.so.com/s?q=abc";
// 将url返回的内容,存入变量result中
String result = this.restTemplate.getForObject(url, String.class);

参数拼接

String url = "https://www.so.com/s?q={keyword}";
Map<String, String> paramMap = new HashMap<>();
paramMap.put("keyword", "abc");
// 将url返回的内容,存入变量result中
String result = this.restTemplate.getForObject(url, String.class, paramMap);

postForEntity 示例

构造 request Object

@Service
public class DataSendService {@Autowiredprivate RestTemplate restTemplate;public void sendData() {String url = "http://localhost:8080/app/data-accept";HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);MultiValueMap<String, String> paramMap= new LinkedMultiValueMap<>();paramMap.add("name", "zhangsan");HttpEntity<MultiValueMap<String, String>> entity = null;entity = new HttpEntity<>(paramMap, headers);ResponseEntity<String> exchange = this.restTemplate.postForEntity(url, entity, String.class);String result = exchange.getBody();System.out.println(result);}
}

在 URL 中传参

@Service
public class DataSendService {@Autowiredprivate RestTemplate restTemplate;public void sendData() {String url = "http://localhost:8080/app/data-accept?name={name}";ResponseEntity<String> exchange = this.restTemplate.postForEntity(url, null, String.class, "zhangsan");System.out.println(exchange.getBody());}
}

postForObject 示例

构造 request Object

@Service
public class DataSendService {@Autowiredprivate RestTemplate restTemplate;public void sendData() {String url = "http://localhost:8080/app/data-accept";HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);MultiValueMap<String, String> paramMap= new LinkedMultiValueMap<>();paramMap.add("name", "zhangsan");HttpEntity<MultiValueMap<String, String>> entity = null;entity = new HttpEntity<>(paramMap, headers);String result = this.restTemplate.postForObject(url, entity, String.class);System.out.println(result);}
}

在 URL 中传参

@Service
public class DataSendService {@Autowiredprivate RestTemplate restTemplate;public void sendData() {String url = "http://localhost:8080/app/data-accept?name={name}";String result = this.restTemplate.postForObject(url, null, String.class, "zhangsan");System.out.println(result);}
}

(POST)Content-Type: application/x-www-form-urlencoded

@Service
public class DataSendService {@Autowiredprivate RestTemplate restTemplate;public void sendData() {String url = "http://localhost:8080/app/data-accept";HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);MultiValueMap<String, String> paramMap= new LinkedMultiValueMap<>();paramMap.add("name", "zhangsan");HttpEntity<MultiValueMap<String, String>> entity = null;entity = new HttpEntity<>(paramMap, headers);String result = this.restTemplate.postForObject(url, entity, String.class);System.out.println(result);}
}

(POST)Content-Type: application/json

@Service
public class DataSendService {@Autowiredprivate RestTemplate restTemplate;public void sendData() {String url = "http://localhost:8080/app/data-accept";HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);JSONObject jsonBody = new JSONObject();jsonBody.put("name", "zhangsan");jsonBody.put("age", 18);HttpEntity<JSONObject> entity = null;entity = new HttpEntity<>(jsonBody , headers);String result = this.restTemplate.postForObject(url, entity, String.class);System.out.println(result);}
}

(POST)Content-Type: application/json

@Service
public class DataSendService {@Autowiredprivate RestTemplate restTemplate;public void sendData() {String url = "http://localhost:8080/app/data-accept";HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.TEXT_PLAIN);String message = "this is a text";HttpEntity<String > entity = null;entity = new HttpEntity<>(message , headers);String result = this.restTemplate.postForObject(url, entity, String.class);System.out.println(result);}
}

postForEntity 与 postForObject 的区别

参数一样,功能一样,返回值类型不一样。

public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType,Object... uriVariables) throws RestClientException {...
}
public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType,Map<String, ?> uriVariables) throws RestClientException {...
}
public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType)throws RestClientException {...
}
public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request,Class<T> responseType, Object... uriVariables) throws RestClientException {...
}
public <T> ResponseEntity<T> postForEntity(String url, @Nullable Object request,Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException {...
}
@Override
public <T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType)throws RestClientException {...
}

【spring boot】 使用 RestTemplate相关推荐

  1. spring boot(5)---RestTemplate请求HTTP(1)

    RestTemplate请求HTTP(1) 说明 传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient.不过此种方法使用起来太过繁琐.spring提供了一种简单 ...

  2. 软件测试 | 测试开发 | Spring boot 之 RestTemplate访问

    什么是RestTemplate ? 传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient.不过此种方法使用起来太过繁琐.Spring提供了一种简单便捷的模板类来 ...

  3. Spring boot 之 RestTemplate

    传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient.不过此种方法使用起来太过繁琐.Spring提供了一种简单便捷的模板类来进行操作,这就是RestTempla ...

  4. Spring Boot的RestTemplate 之exchange方法

    exchange方法提供统一的方法模板进行四种请求:POST,PUT,DELETE,GET import org.springframework.context.annotation.Bean; im ...

  5. Spring Boot 3.0.0-M1 Reference Documentation(Spring Boot中文参考文档) 9-16

    9. 数据 Spring Boot与多个数据技术集成,包括SQL和NoSQL. 9.1. SQL数据库 Spring Framework提供扩展支持用于与SQL数据工作,从使用JdbcTemplate ...

  6. Spring Boot+gRPC构建微服务并部署到Istio(详细教程)

    点击关注公众号,实用技术文章及时了解 作为Service Mesh和云原生技术的忠实拥护者,我却一直没有开发过Service Mesh的应用.正好最近受够了Spring Cloud的"折磨& ...

  7. Spring Boot + WebSocketClient + wss协议证书认证 + 客户端心跳重连机制

    近期公司项目中要对接第三方的WebSocket服务获取数据,本来以为是很简单的工作,但问题是服务方提供的是"wss"协议,需要证书认证,为此查阅了很多博客,都没有解决, 最后还是自 ...

  8. Spring Boot 中的 RestTemplate不好用?试试 Retrofit !

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 作者 | 六点半起床 来源 | juejin.im/post/68 ...

  9. Spring Boot 中的 RestTemplate 不好用?试试 Retrofit!

    大家都知道okhttp是一款由square公司开源的java版本http客户端工具.实际上,square公司还开源了基于okhttp进一步封装的retrofit工具,用来支持通过接口的方式发起http ...

  10. 【spring boot】使用RestTemplate调用微信code2Session接口

    前言 spring boot 2.1.1.RELEASE 使用RestTemplate调用微信code2Session接口 spring boot中使用RestTemplate,参考这里. 调用方法 ...

最新文章

  1. 数组--存储地址的计算
  2. pfSense book之2.4安装指南
  3. 不会玩电脑怎么学计算机,不会玩电脑怎么学
  4. 前几帧预测 深度学习_使用深度学习从十二导联心电图预测心律失常
  5. 【网络】HTTPS 怎么保证数据传输的安全性
  6. mysql如何进行宿舍分配_手把手教你做一个Jsp Servlet Mysql实现的学生宿舍管理系统...
  7. pccad 电气元件_CAD电气元件库谁有?
  8. RxJava2+retrofit实现网络封装
  9. 高等工程数学(一):线性空间
  10. 边缘计算中任务卸载研究综述
  11. 常用的内部网关协议(IGP)
  12. MongoDB 4.2.3 安装以及安装遇到的问题“service MongoDB failed to start,verify that you have sufficient privilege”
  13. 百分制成绩转换五分制F
  14. 追捧《弟子规》,因为你并不知道古代的优质教育是什么
  15. 谷歌云开大会,李飞飞等高管公布多款AI新产品
  16. 10 个实用的 JavaScript 技巧
  17. C语言程序设计课程设计——三国杀游戏
  18. 世界时钟的C语言编码,世界时钟官方下载 世界时钟(Sharp World Clock) 显示多个不同时区当前准确时间 v9.3.5 安装版 下载-脚本之家...
  19. linux vim撤销上次编辑,vim撤销与重做
  20. Type ‘number‘ is not assignable to type ‘string‘

热门文章

  1. 不在JPA 的 persistence.xml 文件里配置Entity class的解决的方法
  2. protobuf使用说明
  3. 用于matplotlib对齐很有用的算法,可用于面试笔试
  4. 距离向量路由环路解决的方法.
  5. 将dataGridView数据转成DataTable
  6. ibatis动态查询条件
  7. C#抓取网页程序的实现浅析
  8. NHibernate错误集锦及配置技巧
  9. php tp5 redis的使用(亲测)
  10. Linux安装Java JDK:方式yum