使用RestTemplate解决Controller内部url请求中文参数乱码的问题

 概述:            

        spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。

用法:

官方api文档:

RestTemplate (Spring Framework 5.3.10 API)

GET 请求

在 RestTemplate 中,和 GET 请求相关的方法有两类:getForEntity 和 getForObject,这里只介绍getForEntity

getForObject  和 getForEntity  的区别

getForObject函数实际上是对getForEntity函数的进一步封装,如果你只关注返回的消息体的内容,对其他信息都不关注,此时可以使用getForObject。

ResponseEntity<T>是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。如果需要提取其中的部分属性的话直接从ResponseEntity中调用相应的方法即可

getForEntity

// RestTemplate发送get请求---不携带任何参数
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> res = restTemplate.getForEntity("http://localhost:8080/user/{id}", String.class);
// 当String类型的url地址中有参数的位置,可以理解为占位符
RestTemplate restTemplate = new RestTemplate();
2 ResponseEntity<String> res = restTemplate.getForEntity("http://localhost:8080/user/{id}", String.class, "1");
// 将参数封装到map集合中传递
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", 11);
ResponseEntity<String> res = restTemplate.getForEntity(
"http://localhost::8080/user/{id}", String.class, map);
String body = res.getBody();//返回的ResponseEntity中包含了头信息,body信息,状态码等信息。

Post请求

postForEntity

1.方法的第一参数表示要调用的服务的地址

2.方法的第二个参数表示上传的参数

3.方法的第三个参数表示返回的消息体的数据类型

Book book = new Book();
book.setName("红楼梦");
ResponseEntity<Book> responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/getbook2", book, Book.class);
responseEntity.getBody().getName();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值