RestTemplate的使用

本文详细介绍了Spring框架中的RestTemplate及其在访问RESTful服务中的应用,包括配置、get和POST请求示例,以及如何携带参数、发送JSON数据和处理cookie等。同时提及了其他常见的HTTP客户端组件如HttpClient和OkHttpClient。
摘要由CSDN通过智能技术生成

目录

一、RestTemplate的简介:

二、常见的http客户端组件:

三、如何使用RestTemplate:

        一、配置RestTemplate 定义访问的http服务的配置类

         二、RestTemplate的快速入门

                3.2.1 get请求携带参数访问外部url

                3.2.2 get请求响应数据自动封装vo实体对象

                3.2.3   请求头携带参数访问外部接口

                3.2.4 POST请求模拟form表单访问外部接口

                3.2.5 POST请求发送JSON数据

                3.2.6  获取接口响应的cookie数据


一、RestTemplate的简介:

       RestTemplate 是 Spring Framework 提供的一个用于访问 RESTful 服务的模板类。它封装了对 HTTP 请求的处理,简化了在 Java 应用程序中与 RESTful 服务进行通信的过程。

        如果想获取股票最新的数据,就需要定时调用第三方接口拉取最新数据流水;

        Spring框架已为我们封装了一套访问远程http接口的模板工具:RestTemplate,借助于该工具,我们可访问第三方股票接口,获取最新数据。 ​ RestTemplate本质上就是一个非常轻量级http客户端,使用简单且容易上手;

二、常见的http客户端组件:

RestTemplate:Spring提供,轻量级容易上手

HttpClient:apache提供

OkHttpClient

三、如何使用RestTemplate:

        一、配置RestTemplate 定义访问的http服务的配置类

        

@Configuration
public class HttpClientConfig(){
    // 定义restTemplate bean
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

         二、RestTemplate的快速入门

                3.2.1 get请求携带参数访问外部url

@SpringBootTest
public class TestRestTemplate {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 测试get请求携带url参数,访问外部接口
     */
    @Test
    public void test01(){
        String url="http://localhost:6666/account/getByUserNameAndAddress?userName=itheima&address=shanghai";
        /*
          参数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);
    }
}

效果 

             

                3.2.2 get请求响应数据自动封装vo实体对象

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

  响应结果:

                3.2.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);
    }

                3.2.4 POST请求模拟form表单访问外部接口

 /**
     * post模拟form表单提交数据
     */
    @Test
    public void test04(){
        String url="http://localhost:6666/account/addAccount";
        //设置请求头,指定请求数据方式
        HttpHeaders headers = new HttpHeaders();
       //告知被调用方,请求方式是form表单提交,这样对方解析数据时,就会按照form表单的方式解析处理
        headers.add("Content-type","application/x-www-form-urlencoded");
        //组装模拟form表单提交数据,内部元素相当于form表单的input框
        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);
    }

效果:

                3.2.5 POST请求发送JSON数据

/**
     * post发送json数据
     */
    @Test
    public void test05(){
        String url="http://localhost:6666/account/updateAccount";
        //设置请求头的请求参数类型
        HttpHeaders headers = new HttpHeaders();
       //告知被调用方,发送的数据格式的json格式,对方要以json的方式解析处理
        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);
    }

                3.2.6  获取接口响应的cookie数据

  /**
     * 获取请求cookie值
     */
    @Test
    public void test06(){
        String url="http://localhost:6666/account/getCookie";
        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);
    }

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值