RestTemplate的使用教程

简介

RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程HTTP服务的方法,能够大大提高客户端的编写效率。

Spring项目配置

引入依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

添加配置交由Spring管理

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(30*1000);
        requestFactory.setReadTimeout(30*1000);
        return new RestTemplate(requestFactory);
    }
}

快速使用

GET请求

无参无请求头的方式

        //GET请求
        //无参无请求头的方式
        RestTemplate restTemplate=new RestTemplate();
        String url1="http://127.0.0.1:9999/test/restTemplateTest";
        JSONObject jsonObject=restTemplate.getForObject(url1, JSONObject.class);
        log.info("GET请求方式,无参无请求头的方式,得到的结果为:{}",jsonObject.toString());

        String url2="http://127.0.0.1:9999/test/restTemplateTest";
        ResponseEntity<JSONObject>  jsonObject1=restTemplate.getForEntity(url1, JSONObject.class);

无参并指定请求头的方式

paraMap为空

        //无参并指定请求头的方式   paramMap是空
        Map<String,Object> paramMap = new HashMap<String,Object>();
        //设置请求头
        HttpHeaders headers=new HttpHeaders();
        headers.add("auth","12345");
        HttpEntity<Object> entity=new HttpEntity<>(paramMap,headers);
        ResponseEntity<JSONObject> result = restTemplate.exchange(url1, HttpMethod.GET,entity, JSONObject.class,paramMap);
        if(result.getStatusCodeValue()==200){
            JSONObject body=result.getBody();
        }

有参的方式

        //有参数的方式
        Map<String,String> paramMap1=new HashMap<>();
        paramMap1.put("userId","123456");
        ResponseEntity<JSONObject> result1=restTemplate.getForEntity(url1+"?userId={userId}", JSONObject.class,paramMap1);
        if(result1.getStatusCodeValue()==200){
            JSONObject body=result1.getBody();
        }

有参数并指定请求头

//有参数并指定请求头
        Map<String,Object> paramMap2=new HashMap<>();
        paramMap2.put("userId","123456");
        //设置请求头
        HttpHeaders headers1=new HttpHeaders();
        headers1.add("auth","123456");
        HttpEntity<Object> entity2=new HttpEntity<>(paramMap2,headers1);
        ResponseEntity<JSONObject> result3=restTemplate.exchange(url1+"?userId={userId}",HttpMethod.GET,entity,JSONObject.class,paramMap2);

优雅地拼接参数

我们可以发现带参数的get请求,如果采用拼接的方式在参数比较少的时候是适用的,但是参数多了的话就比较麻烦。
下面我们通过UriComponentsBuilder来解决

MultiValueMap<String,String> param=new LinkedMultiValueMap<>();
paramMap.add("userId","123456");
UriComponentsBuilder builder=UriComponents.fromHttpUrl(url);
URI uri=builder.queryParams(paramMap).build().encode(StandardCharsets.ISO_8859_1).toUri();

ResponseEntity<JSONObject> result=restTemplate.getForEntity(uri,JSONObject.class);
if(result.getStatusCodeValue()==200){
   JSONObject body=result.getBody();
}

优雅的拼接参数并携带请求头

		MultiValueMap<String, String> multiValueMap = TaskCenterDataConvert.taskSearchDTOToMultiValueMap(taskSearchDTO);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(taskCenterListSearchUrl);
        URI uri = builder.queryParams(multiValueMap).build().encode(StandardCharsets.ISO_8859_1).toUri();

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization","Bearer " + authorization);
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(null, headers);

        ResponseEntity<JSONObject> result = restTemplate.exchange(uri.toString(), HttpMethod.GET, httpEntity, JSONObject.class, multiValueMap);
        if (result.getStatusCodeValue() == 200){
            JSONObject body = result.getBody();
          
            }
        }

getForObject.getForEntity和exchange的区别

  • getForObject返回值直接是响应体内容转换为指定的对象;
  • getForEntity返回值的封装包含有响应头,响应状态码的ResponseEntity对象;
  • exchange可以指定为get请求或者post请求,并且返回ResponseEntity对象。

POST请求

application/json的方式

具体参数可以指定为map,json或者bean的形式;

Map<String,String> paramMap=new HashMap<>();
paramMap.put("userId","123456");
//设置请求头
HttpHeaders headers=new HttpHeaders();
headers.add("Content-Type","application/json");
headers.add("auth","123456789");
HttpEntity<Object> entity=new HttpEntity<Object>(paramMap,heanders);
JSONObject result=restTemplate.postForObject(url,entity,JSONObject.class);

表单的方式

MultiValueMap<String,String> paramMap = new LinkedMuiltiValueMap<>();
paramMap.put("userId","123456");
//设置请求头
HttpHeaders headers=new HttpHeaders();
headers.add("Content-Type","application/x-www-form-urlencode");
headers.add("auth","123456");
HttpEntity<Object> entity=new HttpEntity<Object>(paramMap,headers);
JSONObject result=restTemplate.postForObject(url,entity,JSONObject.class);

注意:
使用RestTemplate提交表单时必须使用MultiValueMap来传参
是因为用HashMap定义的参数在使用表单方式传递的时候,最终数据是以json形式传过去的。

相关推荐

  1. RestTemplate使用教程

    2024-04-10 02:54:01       28 阅读
  2. spring restTemplate使用和学习总结

    2024-04-10 02:54:01       33 阅读
  3. Springboot中RestTemplate

    2024-04-10 02:54:01       57 阅读
  4. RestTemplate应用

    2024-04-10 02:54:01       40 阅读
  5. springboot中使用RestTemplate 请求http接口

    2024-04-10 02:54:01       32 阅读
  6. RestTemplate异常重试机制

    2024-04-10 02:54:01       27 阅读
  7. conda使用教程

    2024-04-10 02:54:01       48 阅读
  8. jmeter使用教程

    2024-04-10 02:54:01       57 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-10 02:54:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-10 02:54:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-10 02:54:01       87 阅读
  4. Python语言-面向对象

    2024-04-10 02:54:01       96 阅读

热门阅读

  1. [鹤城杯 2021]Crazy_Rsa_Tech(低加密指数广播攻击)

    2024-04-10 02:54:01       34 阅读
  2. Oracle测试10046参数及打印结果

    2024-04-10 02:54:01       37 阅读
  3. Go语言中如何实现继承

    2024-04-10 02:54:01       39 阅读
  4. c++ 根据ip主机号和子网掩码随机生成ip

    2024-04-10 02:54:01       39 阅读
  5. 深入理解JVM后端优化技术-锁消除(Lock Elision)

    2024-04-10 02:54:01       37 阅读
  6. C++中的字符转换 to_string、sto

    2024-04-10 02:54:01       37 阅读
  7. Qt实现comboBox的初试化

    2024-04-10 02:54:01       38 阅读
  8. Go 中无缓冲通道与容量为1的缓冲通道的区别

    2024-04-10 02:54:01       35 阅读
  9. Object.is方法和==和===区别

    2024-04-10 02:54:01       34 阅读
  10. 工业通信原理——Modbus物理层简介

    2024-04-10 02:54:01       35 阅读