RestTemplate使用详解

简介: 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


1)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);
    }


效果:



2)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);
    }


效果:



3)获取接口响应的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);
    }


效果:


相关文章
|
Java API Spring
SpringBoot项目调用HTTP接口5种方式你了解多少?
SpringBoot项目调用HTTP接口5种方式你了解多少?
3418 2
|
12月前
|
JSON Java 数据格式
Object转JSON
该方法将Java对象转换为JSON字符串,使用JSONArray.fromObject实现序列化,并输出转换结果日志,最后返回生成的JSON字符串。适用于对象数据的JSON格式化处理。
|
存储 缓存 NoSQL
Redisson中的RScoredSortedSet的常见使用场景及排行榜例子
通过本文的介绍,我们详细讲解了Redisson中RScoredSortedSet的常见使用场景及其基本操作,并通过具体示例展示了如何实现一个简单的排行榜功能。RScoredSortedSet在需要按分值排序和检索数据的场景中非常有用,希望本文能帮助您更好地理解和应用RScoredSortedSet,构建高效的Redis应用。
1166 15
|
Java Spring
springboot使用RestTemplate(基于2.6.7,返回泛型)
springboot使用RestTemplate(基于2.6.7,返回泛型)
898 0
|
Java Spring 容器
基于RestTemplate扩展,支持Get请求传递javaBean参数
本文介绍了如何扩展RestTemplate以支持在GET请求中传递JavaBean参数的问题。在项目中,作者发现使用RestTemplate进行GET请求时,不能直接传递JavaBean作为参数,而需要手动将参数拼接到URL中,这种方法不仅繁琐而且容易出错
基于RestTemplate扩展,支持Get请求传递javaBean参数
|
JSON Java API
解码Spring Boot与JSON的完美融合:提升你的Web开发效率,实战技巧大公开!
【8月更文挑战第29天】Spring Boot作为Java开发的轻量级框架,通过`jackson`库提供了强大的JSON处理功能,简化了Web服务和数据交互的实现。本文通过代码示例介绍如何在Spring Boot中进行JSON序列化和反序列化操作,并展示了处理复杂JSON数据及创建RESTful API的方法,帮助开发者提高效率和应用性能。
1082 0
|
Java API Maven
SpringBoot 调用外部接口的三种方式--学习总结
SpringBoot 调用外部接口的三种方式--学习总结
1119 1
|
Web App开发 Java 网络安全
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
5474 0
|
JSON 数据格式
接口调用神器RestTemplate(三)
接口调用神器RestTemplate
870 0
|
负载均衡 Java API