RestTemplate中的请求方式的应用

什么是RestTemplate?

RestTemplate是Spring框架中的一个用于访问RESTful服务的模板类。它提供了一组方便的方法来发送HTTP请求并处理响应。

RestTemplate可以用来发送GET、POST、PUT、DELETE等类型的请求,并可以处理JSON、XML等多种格式的响应数据。

在Spring中使用RestTemplate可以简化与RESTful服务的交互,使得开发者可以更加方便地进行HTTP通信。

以下是一个使用RestTemplate发送GET请求的示例代码:

RestTemplate restTemplate = new RestTemplate();
String url = "https://api.example.com/data";
String response = restTemplate.getForObject(url, String.class);
System.out.println(response);

GET 

<T> T getForObject(String url, Class<T> responseType, Object... uriVariables);
 
<T> T getForObject(String url, Class<T> responseType, Map<String, ?> uriVariables);
 
<T> T getForObject(URI url, Class<T> responseType);
 
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables);
 
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables);
 
<T> ResponseEntity<T> getForEntity(URI var1, Class<T> responseType);
 

POST

<T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables);
 
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables);
 
<T> T postForObject(URI url, @Nullable Object request, Class<T> responseType);
 
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables);
 
<T> ResponseEntity<T> postForEntity(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables);
 
<T> ResponseEntity<T> postForEntity(URI url, @Nullable Object request, Class<T> responseType);

 

下面就来说几个最常用的API:

GET

1.gettForObject

返回对象为响应体中数据转化成的对象,基本上可以理解为Json

例如:按照主键查找流水信息(微服务中的远程调用)

    @GetMapping("/consumer/pay/get/{id}")
    public ResultData getPayInfo(@PathVariable("id") Integer id){
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/"+id, ResultData.class, id);

    }

返回结果如下:

2.getForEntity

返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等。

具体使用方法和上述类似,只不过返回值会返回响应头信息。。

POST

1.postForObject

例如,远程添加订单信息:

    /**
     * 一般情况下,通过浏览器的地址栏输入url,发送的只能是get请求
     * 我们底层调用的是post方法,模拟消费者发送get请求,客户端消费者
     * 参数可以不添加@RequestBody
     * @param payDTO
     * @return
     */
    @GetMapping("/consumer/pay/add")
    public ResultData addOrder(PayDTO payDTO){
        return restTemplate.postForObject(PaymentSrv_URL + "/pay/add",payDTO,ResultData.class);
    }

2.postForEntity

和postForObject类似, 不过postForEntity方法中可以设置header的属性,

当需要指定header的属性值的时候,使用postForEntity方法。

postForObject和postForEntity方法的区别主要在于可以在postForEntity方法中设置header的属性,当需要指定header的属性值的时候,使用postForEntity方法。

exchange方法和postForEntity类似,但是更灵活,exchange还可以调用get、put、delete请求。使用这三种方法调用post请求传递参数,Map不能定义为以下两种类型(url使用占位符进行参数传递时除外)

Map<String, Object> paramMap = new HashMap<String, Object>();
Map<String, Object> paramMap = new LinkedHashMap<String, Object>();

3.exchange

非常灵活,推荐使用。

其中可以调用HTTP所属类的方法,源码如下

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.http;

import java.io.Serializable;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

public final class HttpMethod implements Comparable<HttpMethod>, Serializable {
    private static final long serialVersionUID = -70133475680645360L;
    public static final HttpMethod GET = new HttpMethod("GET");
    public static final HttpMethod HEAD = new HttpMethod("HEAD");
    public static final HttpMethod POST = new HttpMethod("POST");
    public static final HttpMethod PUT = new HttpMethod("PUT");
    public static final HttpMethod PATCH = new HttpMethod("PATCH");
    public static final HttpMethod DELETE = new HttpMethod("DELETE");
    public static final HttpMethod OPTIONS = new HttpMethod("OPTIONS");
    public static final HttpMethod TRACE = new HttpMethod("TRACE");
    private static final HttpMethod[] values;
    private final String name;

    private HttpMethod(String name) {
        this.name = name;
    }

    public static HttpMethod[] values() {
        HttpMethod[] copy = new HttpMethod[values.length];
        System.arraycopy(values, 0, copy, 0, values.length);
        return copy;
    }

    public static HttpMethod valueOf(String method) {
        Assert.notNull(method, "Method must not be null");
        HttpMethod var10000;
        switch (method) {
            case "GET":
                var10000 = GET;
                break;
            case "HEAD":
                var10000 = HEAD;
                break;
            case "POST":
                var10000 = POST;
                break;
            case "PUT":
                var10000 = PUT;
                break;
            case "PATCH":
                var10000 = PATCH;
                break;
            case "DELETE":
                var10000 = DELETE;
                break;
            case "OPTIONS":
                var10000 = OPTIONS;
                break;
            case "TRACE":
                var10000 = TRACE;
                break;
            default:
                var10000 = new HttpMethod(method);
        }

        return var10000;
    }

    public String name() {
        return this.name;
    }

    public boolean matches(String method) {
        return this.name().equals(method);
    }

    public int compareTo(HttpMethod other) {
        return this.name.compareTo(other.name);
    }

    public int hashCode() {
        return this.name.hashCode();
    }

    public boolean equals(@Nullable Object other) {
        boolean var10000;
        if (this != other) {
            label26: {
                if (other instanceof HttpMethod) {
                    HttpMethod that = (HttpMethod)other;
                    if (this.name.equals(that.name)) {
                        break label26;
                    }
                }

                var10000 = false;
                return var10000;
            }
        }

        var10000 = true;
        return var10000;
    }

    public String toString() {
        return this.name;
    }

    static {
        values = new HttpMethod[]{GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE};
    }
}

可以看到,平时常用到的Put,Post,Get,Delete方法全部包括在内了

下面简单使用一下,根据主键远程删除一条数据:

    @DeleteMapping("/consumer/pay/del/{id}")
    public Object delOrder(@PathVariable("id") Integer id) {
        return restTemplate.exchange(PaymentSrv_URL + "/pay/del/" + id, HttpMethod.DELETE, null, ResultData.class).getBody();
    }

postman返回结果

非常之方便....

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值