如何优雅的使用 RestTemplate

导读:本篇文章讲解 如何优雅的使用 RestTemplate,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一、概述

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

二、配置

1、引入依赖

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

2、添加配置交由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);
    }
}

三、快速使用

1、GET请求

1.1、无参无请求头的方式

		String url="http://127.0.0.1:9999/test/restTemplateTest";
		JSONObject jsonObject = restTemplate.getForObject(url,JSONObject.class);
		String url="http://127.0.0.1:9999/test/restTemplateTest";
		ResponseEntity<JSONObject> jsonObject = restTemplate.getForEntity(url,JSONObject.class);

1.2、无参并指定请求头的方式
paramMap 是空

		Map<String, Object> paramMap = new HashMap<String, Object>();
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("auth","123445");
        HttpEntity<Object> entity = new HttpEntity<>(paramMap,headers);
        ResponseEntity<JSONObject> result = restTemplate.exchange(url, HttpMethod.GET, entity, JSONObject.class, paramMap);
        if (result.getStatusCodeValue() == 200){
            JSONObject body = result.getBody();
        }

1.3、有参的方式
记得要在url中拼接参数 url + “?userId={userId}”

		Map<String, String> paramMap = new HashMap<>();
        paramMap.put("userId", "123456");
        ResponseEntity<JSONObject> result = restTemplate.getForEntity(url + "?userId={userId}", JSONObject.class, paramMap);
        if (result.getStatusCodeValue() == 200){
            JSONObject body = result.getBody();
        }

1.4、有参并指定请求头

		Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", "123456");
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("auth","123445");
        HttpEntity<Object> entity = new HttpEntity<>(paramMap,headers);
        ResponseEntity<JSONObject> result = restTemplate.exchange(url + "?userId={userId}", HttpMethod.GET, entity, JSONObject.class, paramMap);
        if (result.getStatusCodeValue() == 200){
            JSONObject body = result.getBody();
        }

1.5、优雅的拼接参数

我们发现带参数的get请求需要将参数拼接到url中,参数少好说,参数多了就很麻烦
我们使用UriComponentsBuilder来解决

		MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("userId", "123456");
        UriComponentsBuilder builder = UriComponentsBuilder.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();
        }

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

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

1.7、getForObject 、getForEntity和exchange 区别

post请求也是相同的道理

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

2、POST请求

2.1、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","12334455666");
        HttpEntity<Object> entity = new HttpEntity<Object>(paramMap,headers);
        JSONObject result = restTemplate.postForObject(url, entity,JSONObject.class);

2.1、表单的方式

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

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

MultiValueMap 和 Map的区别:

MultiValueMap 一个 key 可以对应多个 value
Map 一个 key 对应一个 value

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/99533.html

(0)
小半的头像小半

相关推荐

极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!