RsetTemplate用法

RsetTemplate用法

RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求、POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 exchange 以及 execute。

1. 配置RsetTemplate

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
}

2. GET请求

定义一个get请求的接口:

@GetMapping("/hello")
public String sayHello(String name){
    return "hello " + name;
}

包含getForEntity和getForObject方法。

2.1 getForEntity

可以获取响应数据和响应头信息,getForEntity有三个重载方法:

2.1.1 getForEntity(String url, Class<T> responseType, Object… uriVariables)

第一个参数是 url,url 中有一个占位符 {1} ,如果有多个占位符分别用 {2} 、 {3} … 去表示,第二个参数是接口返回的数据类型,最后是一个可变长度的参数,用来给占位符填值。

@Autowired
private RestTemplate restTemplate;

@GetMapping("/hello1")
public String hello1(String name){
    //url 中有一个占位符 {1} ,如果有多个占位符分别用 {2} 、 {3} … 去表示
    String url = "http://localhost:3001/hello?name={1}";
    ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, name);
    StringBuilder sb = new StringBuilder();
    //响应状态码
    HttpStatus statusCode = responseEntity.getStatusCode();
    //响应内容
    String body = responseEntity.getBody();
    sb.append("statusCode:")
            .append(statusCode)
            .append("<br>")
            .append("body:")
            .append(body)
            .append("<br>");
    //响应头
    HttpHeaders headers = responseEntity.getHeaders();
    Set<String> keySet = headers.keySet();
    for (String s : keySet) {
        sb.append(s)
                .append(":")
                .append(headers.get(s))
                .append("<br>");
    }
    return sb.toString();
}
2.1.2 getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables)

第一个参数是 url ,url 中有一个占位符 {},不是数字,而使用参数的key,第二个参数是接口返回的数据类型,最后是一个map参数。

@Autowired
private RestTemplate restTemplate;

@GetMapping("/hello2")
public String hello2(String name){
    //url 中有一个占位符 {},不是数字,而使用参数的key
    String url = "http://localhost:3001/hello?name={name}";
    Map<String, Object> map = new HashMap<>();
    map.put("name",name);
    ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, map);
    StringBuilder sb = new StringBuilder();
    //响应状态码
    HttpStatus statusCode = responseEntity.getStatusCode();
    //响应状态
    String body = responseEntity.getBody();
    sb.append("statusCode:")
            .append(statusCode)
            .append("<br>")
            .append("body:")
            .append(body)
            .append("<br>");
    //响应头
    HttpHeaders headers = responseEntity.getHeaders();
    Set<String> keySet = headers.keySet();
    for (String s : keySet) {
        sb.append(s)
                .append(":")
                .append(headers.get(s))
                .append("<br>");
    }
    return sb.toString();
}
2.2.3 getForEntity(URI url, Class<T> responseType)

第一个参数是 url ,url 中使用URI对象,参数如果是中文的话,需要对参数进行编码,使用 URLEncoder.encode 方法来实现,第二个参数是接口返回的数据类型。

@Autowired
private RestTemplate restTemplate;

@GetMapping("/hello3")
public String hello3(String name) throws UnsupportedEncodingException {
    //url 中使用URI对象,参数如果是中文的话,需要对参数进行编码,使用 URLEncoder.encode 方法来实现
    String url = "http://localhost:3001/hello?name=" + URLEncoder.encode(name,"UTF-8");
    URI uri = URI.create(url);
    ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
    StringBuilder sb = new StringBuilder();
    //响应状态码
    HttpStatus statusCode = responseEntity.getStatusCode();
    //响应状态
    String body = responseEntity.getBody();
    sb.append("statusCode:")
        .append(statusCode)
        .append("<br>")
        .append("body:")
        .append(body)
        .append("<br>");
    //响应头
    HttpHeaders headers = responseEntity.getHeaders();
    Set<String> keySet = headers.keySet();
    for (String s : keySet) {
        sb.append(s)
            .append(":")
            .append(headers.get(s))
            .append("<br>");
    }
    return sb.toString();
}

2.2 getForObject

getForObject 的返回值就是服务提供者返回的数据,使用 getForObject 无法获取到响应头。也是有三种重载方法,使用方式与getForEntity一致。

@Autowired
private RestTemplate restTemplate;

@GetMapping("/hello4")
public String hello4(String name) {
    String url = "http://localhost:3001/hello?name={1}";
    return restTemplate.getForObject(url, String.class,name);
}

3. POST请求

定义post请求接口(一个String一个对象):

@PostMapping("/hi")
public String sayHi(@RequestBody String name){
    return "hi " + name;
}

@PostMapping("/user")
public String sayHa(@RequestBody User user){
    return "hi " + user;
}

包含 postForEntity 、 postForObject和postForLocation方法。

3.1 postForEntity

可以获取响应数据和响应头信息,postForEntity 有三个重载方法:

3.1.1 postForEntity(String url, @Nullable Object request,Class<T> responseType, Object… uriVariables)

以key/value形式:

@Autowired
private RestTemplate restTemplate;

public String hi1() {
    String name = "hah";
    String url = "http://localhost:3001/hi?name={1}";
    ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, null, String.class, name);
    return responseEntity.getBody();
}

还有一种方式,以LinkedMultiValueMap的方式作为请求体。

@Autowired
private RestTemplate restTemplate;

public String hi2(){
    String name = "hah";
    String url = "http://localhost:3001/hi";
    MultiValueMap<String,Object> map = new LinkedMultiValueMap<>();
    map.put("name", Collections.singletonList(name));
    HttpHeaders httpHeaders = new HttpHeaders();
    HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map,httpHeaders);
    //这里第二个参数需要header就使用httpEntity,不需要可以直接map
    ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
    StringBuilder sb = new StringBuilder();
    //响应状态码
    HttpStatus statusCode = responseEntity.getStatusCode();
    //响应状态
    String body = responseEntity.getBody();
    sb.append("statusCode:")
            .append(statusCode)
            .append("<br>")
            .append("body:")
            .append(body)
            .append("<br>");
    //响应头
    HttpHeaders headers = responseEntity.getHeaders();
    Set<String> keySet = headers.keySet();
    for (String s : keySet) {
        sb.append(s)
                .append(":")
                .append(headers.get(s))
                .append("<br>");
    }
    return sb.toString();
}

以JSON形式:

如果是请求参数是对象,会转为json的形式发送。

public String hi3() {
    String url = "http://localhost:3001/user";
    User user = new User();
    user.setId(1);
    user.setName("张三");
    ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, user, String.class);
    return responseEntity.getBody();
}
3.1.2 postForEntity(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)
3.1.3 postForEntity(URI url, @Nullable Object request, Class<T> responseType)

3.2 postForObject

postForObject 和 postForEntity类似,返回类型不同。

3.3 postForLocation

postForLocation返回值为URI对象,所以请求的接口必须是一个重定向接口,否则会返回null。

生产者定义重定向接口:

@PostMapping("/redirect")
public String redirect(@RequestBody String name) throws UnsupportedEncodingException {
    return "redirect:/index";
}

在消费者调用该请求:

public String hi4() {
    String name = "hah";
    String url = "http://localhost:3001/redirect";
    MultiValueMap<String,Object> map = new LinkedMultiValueMap<>();
    map.put("name", Collections.singletonList(name));
    URI uri = restTemplate.postForLocation(url, map);
    return String.valueOf(uri);
}

执行后返回http://localhost:3001/index

4. exchange方法

exchange方法为通用方法,可以在该方法的参数中指定请求类型,用法大同小异。

public String hello7(String name) {
    String url = "http://localhost:3001/hello?name={1}";
    ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, null, String.class, name);
    return exchange.getBody();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小辰~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值