RestTemplate使用详解

在这里插入图片描述


RestTemplate是Spring提供的一个用于访问RESTful Web服务的客户端工具。它可以方便地处理HTTP请求和响应,支持多种HTTP方法(GET、POST、PUT等),并且能够将服务器返回的JSON、XML等数据自动转换成Java对象。


在这里插入图片描述

1.1 RestTemplate环境准备

1)背景说明
Spring 框架已为我们封装了一套后端访问http接口的模板工具:RestTemplate。
RestTemplate非常轻量级,使用简单易上手。

2)工程配置RestTemplate

在stock_backend工程下配置RestTemplate bean:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @Description 定义访问http服务的配置类
 */
@Configuration
public class HttpClientConfig {
    /**
     * 定义restTemplate bean
     * @return
     */
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}


在这里插入图片描述

1.2 RestTemplate API入门-1

1)get请求携带参数访问外部url
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * @Description
 */
@SpringBootTest
public class TestRestTemplate {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 测试get请求携带url参数,访问外部接口
     */
    @Test
    public void test01(){
        String url="";
        /*
          参数1:url请求地址
          参数2:请求返回的数据类型
         */
        ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
        //获取响应头
        HttpHeaders headers = result.getHeaders();
        System.out.println(headers.toString());
        //响应状态码
        int statusCode = result.getStatusCodeValue();
        System.out.println(statusCode);
        //响应数据
        String respData = result.getBody();
        System.out.println(respData);
    }
}

效果:
在这里插入图片描述


2)get请求响应数据自动封装vo实体对象
    /**
     * 测试响应数据自动封装到vo对象
     */
    @Test
    public void test02(){
        String url="";
        /*
          参数1:url请求地址
          参数2:请求返回的数据类型
         */
        Account account = restTemplate.getForObject(url, Account.class);
        System.out.println(account);
    }

    @Data
    public static class Account {

        private Integer id;

        private String userName;

        private String address;
        
    }

效果:

在这里插入图片描述


3)请求头携带参数访问外部接口
    /**
     * 请求头设置参数,访问指定接口
     */
    @Test
    public void test03(){
        String url="http://localhost:6666/account/getHeader";
        //设置请求头参数
        HttpHeaders headers = new HttpHeaders();
        headers.add("userName","zhangsan");
        //请求头填充到请求对象下
        HttpEntity<Map> entry = new HttpEntity<>(headers);
        //发送请求
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entry, String.class);
        String result = responseEntity.getBody();
        System.out.println(result);
    }

效果:

在这里插入图片描述



在这里插入图片描述

1.3 RestTemplate API入门-2

4)POST请求模拟form表单访问外部接口
    /**
     * post模拟form表单提交数据
     */
    @Test
    public void test04(){
        String url="";
        //设置请求头,指定请求数据方式
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-type","application/x-www-form-urlencoded");
        //组装模拟form表单提交数据
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("id","10");
        map.add("userName","itheima");
        map.add("address","shanghai");
        HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map, headers);
        /*
            参数1:请求url地址
            参数2:请求方式 POST
            参数3:请求体对象,携带了请求头和请求体相关的参数
            参数4:响应数据类型
         */
        ResponseEntity<Account> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Account.class);
        Account body = exchange.getBody();
        System.out.println(body);
    }

效果:

在这里插入图片描述


5)POST请求发送JSON数据
    /**
     * post发送json数据
     */
    @Test
    public void test05(){
        String url="";
        //设置请求头的请求参数类型
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-type","application/json; charset=utf-8");
        //组装json格式数据
//        HashMap<String, String> reqMap = new HashMap<>();
//        reqMap.put("id","1");
//        reqMap.put("userName","zhangsan");
//        reqMap.put("address","上海");
//        String jsonReqData = new Gson().toJson(reqMap);
        String jsonReq="{\"address\":\"上海\",\"id\":\"1\",\"userName\":\"zhangsan\"}";
        //构建请求对象
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonReq, headers);
          /*
            发送数据
            参数1:请求url地址
            参数2:请求方式
            参数3:请求体对象,携带了请求头和请求体相关的参数
            参数4:响应数据类型
         */
        ResponseEntity<Account> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Account.class);
      //或者
     // Account account=restTemplate.postForObject(url,httpEntity,Account.class);
        Account body = responseEntity.getBody();
        System.out.println(body);
    }

效果:

在这里插入图片描述


6)获取接口响应的cookie数据
    /**
     * 获取请求cookie值
     */
    @Test
    public void test06(){
        String url="";
        ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
        //获取cookie
        List<String> cookies = result.getHeaders().get("Set-Cookie");
        //获取响应数据
        String resStr = result.getBody();
        System.out.println(resStr);
        System.out.println(cookies);
    }

效果:

在这里插入图片描述


在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Java中的RestTemplateSpring框架提供的一个用于访问RESTful服务的客户端工具。它提供了一组用于HTTP请求的方法,使得我们能够方便地与RESTful服务进行交互。下面是使用RestTemplate的详细步骤。 1. 引入依赖 在pom.xml文件中引入RestTemplate依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.3.0.RELEASE</version> </dependency> ``` 2. 创建RestTemplate对象 可以通过Spring的依赖注入来创建RestTemplate对象,也可以直接new一个对象。下面是使用依赖注入创建RestTemplate对象的示例: ``` @Autowired private RestTemplate restTemplate; ``` 3. 发送HTTP请求 RestTemplate提供了多种发送HTTP请求的方法,包括GET、POST、PUT、DELETE等。这里以GET请求为例: ``` String url = "http://example.com/get?param1=value1&param2=value2"; String result = restTemplate.getForObject(url, String.class); ``` 其中,url是请求的URL地址,result是响应的字符串。getForObject()方法会将响应的JSON字符串转换成Java对象并返回。 4. 发送带有参数的HTTP请求 可以通过RestTemplate的exchange()方法发送带有参数的HTTP请求: ``` String url = "http://example.com/post"; MultiValueMap<String, String> params= new LinkedMultiValueMap<>(); params.add("param1", "value1"); params.add("param2", "value2"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers); String result = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class).getBody(); ``` 其中,url是请求的URL地址,params是请求的参数,headers是请求头,requestEntity是请求体,result是响应的字符串。 5. 发送带有请求体的HTTP请求 可以通过RestTemplate的postForObject()方法发送带有请求体的HTTP请求: ``` String url = "http://example.com/post"; String requestJson = "{\"param1\":\"value1\",\"param2\":\"value2\"}"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> requestEntity = new HttpEntity<>(requestJson, headers); String result = restTemplate.postForObject(url, requestEntity, String.class); ``` 其中,url是请求的URL地址,requestJson是请求的JSON字符串,headers是请求头,requestEntity是请求体,result是响应的字符串。 6. 处理响应 RestTemplate发送的HTTP请求的响应可以是字符串、字节数组、输入流、Java对象等。可以根据需要选择不同的处理方式: ``` // 响应为字符串 String result = restTemplate.getForObject(url, String.class); // 响应为字节数组 byte[] result = restTemplate.getForObject(url, byte[].class); // 响应为输入流 InputStream result = restTemplate.getForObject(url, InputStream.class); // 响应为Java对象 Response response = restTemplate.getForObject(url, Response.class); ``` 这里的Response是一个Java对象,它的属性与响应的JSON字符串对应。可以通过使用Jackson等JSON转换框架将JSON字符串转换成Java对象。 以上就是使用RestTemplate发送HTTP请求的详细步骤。需要注意的是,RestTemplate在处理HTTP请求时,会抛出一些异常,例如HttpStatusCodeException、ResourceAccessException等,需要进行适当的异常处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

我有一颗五叶草

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

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

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

打赏作者

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

抵扣说明:

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

余额充值