前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >RestTemplate用法

RestTemplate用法

作者头像
鱼找水需要时间
发布2023-02-16 15:27:32
3810
发布2023-02-16 15:27:32
举报
文章被收录于专栏:SpringBoot教程
  • RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求、POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 exchange 以及 execute。RestTemplate 继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口,其中 RestOperations 接口定义了基本的 RESTful 操作,这些操作在 RestTemplate 中都得到了实现。

使用

  1. 新建 config.ApplicationContextConfig.java
代码语言:javascript
复制
@Configuration
public class ApplicationContextConfig {

    @Bean // applicationContext.xml <bean id="" class="">
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
  1. 使用
代码语言:javascript
复制
    @Resource
    private RestTemplate restTemplate;

    @GetMapping(value = "/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment) {
        return restTemplate.postForObject(“http://localhost:8080” + "/payment/get/" + id, payment, CommonResult.class);
        
        // (url, requestMap, ResponseBean.class) 这三个参数分别代表
        // REST请求地址、请求参数、HTTP响应被转换成的对象类型
        // 支持的方法很多,不一一列举了
    }
    @GetMapping(value = "/consumer/payment/getForEntity/{id}")
    public CommonResult getpaymentlist2(@PathVariable("id") Long id) {
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);

        if (entity.getStatusCode().is2xxSuccessful()){
        	// log.info(entity.getHeaders());
            return entity.getBody();
        }else {
            return new CommonResult(444,"查询失败");
        }
    }
  1. 添加请求头和body
代码语言:javascript
复制
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;


private static String formUpload(){
    HttpHeaders httpHeaders = new HttpHeaders();
    
    httpHeaders.set("token","123");
    httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    
     //  封装参数,千万不要替换为Map与HashMap,否则参数无法传递
    MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
    multiValueMap.add("api_key", API_KEY);
    multiValueMap.add("api_secret", API_SECRET);
    
    HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(multiValueMap, httpHeaders);
    return restTemplate.postForObject(serverUrl, httpEntity, String.class);
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-06-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档