Spring对发送Http请求的支持,RestTemplate中文乱码解决,RestTemplate发送json数据,RestTemplate上传文件


官方网址:https://spring.io/guides/gs/consuming-rest/

一、前提

创建SpringBoot项目,我的版本为2.2.6
引入依赖,如下

<!-- 必需:Spring-Web模块 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- 可选:处理JSON数据相关的包 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.68</version>
</dependency>

<!-- 可选:单元测试 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

二、简介

1. 总览

只对restful 四种请求方式进行说明

HTTP MethodRestTemplate methods
GETgetForObject
getForEntity
POSTpostForObject
postForEntity
postForLocation
PUTput
DELETEdelete

2. exchange() 和 execute()

这两个方法和上述方法使用方式一致,只是多了一个参数,来指定HttpMethod。类比于SpringMVC,如 @PostMapping(value = “models”)和@RequestMapping(value = “model”, method = RequestMethod.POST)

3. xxxForObject()和xxxForEntity(),exchange()和execute() 区别

代码实例:

String response = template.postForObject(url, requestEntity, String.class);
ResponseEntity<String> responseEntity = template.postForEntity(url, requestEntity, String.class);

xxxForObject()和execute(),我们只需要关心响应体(Response Body),Spring帮助我们将响应体数据封装成我们期望的数据类型。
xxxForEntity()和exchange(),我们关心的是整个响应(Response)

三、案例

0. 解决中文乱码问题

将默认编码 ISO-8859-8 --> UTF-8

public static void encondingConvert(RestTemplate template){
      List<HttpMessageConverter<?>> converters = template.getMessageConverters();
      Iterator<HttpMessageConverter<?>> iterator = converters.iterator();
      while(iterator.hasNext()){
          HttpMessageConverter<?> converter = iterator.next();
          if(converter instanceof StringHttpMessageConverter){
              ((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
          }
      }
  }

1. get请求,使用url变量

@Test
public void doGet() {
    RestTemplate template = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "bearer jRSTh9WCVRVuENeutdoBJw1d2sUXYO");
    headers.set("Accept", "*/*");

    HttpEntity request = new HttpEntity(headers);

    /** 由于getForObject()和getForEntity()不能封装请求头,所以此处使用exchange() */

    /** 使用restful风格,使用占位符 */
    String url = "http://127.0.0.1:9999/product/images/{1}";
	Integer urlVariavle = 313926502;
	ResponseEntity<String> response = template.exchange(url, HttpMethod.GET, request, String.class, urlVariavle);

    System.out.println(response.getBody());
}

2. post请求,默认发送json格式数据

@Test
public void doPost(){
	 /** 获取Spring提供的rest模板对象,构建一个Http客户端 */
     RestTemplate template = new RestTemplate();

	 /** 解决中文乱码问题:调用 0中方法 */
     encondingConvert(template);

     /** 获取Header对象 */
     HttpHeaders httpHeaders = new HttpHeaders();
     /** 设置Content-Type:application/json */
     httpHeaders.setContentType(MediaType.APPLICATION_JSON);
     /** 请求头添加其他信息,如token等 */
     httpHeaders.set("Accept","*/*");
     httpHeaders.set("Authorization","bearer jRSTh9WCVRVuENeutdoBJw1d2sUXYO");

     /** 请求体的数据 */
     Map<String, String> map = new HashMap<>();
     map.put("model_desc", "这是一个描述");
     map.put("region", "CLINDER");
     map.put("user", "zhaocy@briup.com");
     /** 
     	description: 将请求体和请求头封装成Http request
     	param1: 请求体,传入map或字符串;
     		底层会将map转成json格式数据,或直接传入json格式字符串
     	param2: 请求头
     */
     HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(map, httpHeaders);

     String url = "http://127.0.0.1:9999/product/models";
     /** 
		description: 发送post请求
		method: postForObject
		param1: 服务器url
		param2: 上面封装好的Http request
		param3: Class类型,响应体的类型:可以String;
			可以是自定义实体类,内部自动将响应体封装实体类对象;
			可以是集合、数组
		return: param3的Class类型
	 */
     // String response = template.postForObject(url, requestEntity, String.class);
     
     /**
		postForEntity()与postForObject()的区别:
		return: Http response类型,对response的操作更多,可以查看完整的resopnse
	 */
     ResponseEntity<String> responseEntity = template.postForEntity(url, requestEntity, String.class);
     System.out.println(responseEntity.getBody());
 }

3. put请求,文件上传

@Test
public void doPut() {
    RestTemplate template = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    headers.set("Authorization","bearer jRSTh9WCVRVuENeutdoBJw1d2sUXYO");
    headers.set("Accept","*/*");

    /** 使用FileSystemResource,获取本地的文件 */
    String filePath = "C:\\Users\\zhaocy\\Desktop\\jdk api 1.8.CHM";
    FileSystemResource resource = new FileSystemResource(filePath);

    /** 使用接口MultiValueMap,是Map的子类 */
    MultiValueMap<String, Object> map = new LinkedMultiValueMap();
    /** 使用add(),非put() */
    map.add("model", resource);

    HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);

    String url = "http://127.0.0.1:9999/product/models/" + 1615058163;

    /** 由于put()返回值类型:void,此处使用exchange()提交put请求 */
    // template.put(url, request);
    ResponseEntity<String> response = template.exchange(url, HttpMethod.PUT, request, String.class);
    System.out.println(response.getBody());
}

未完待续
本文参考链接:
https://www.cnblogs.com/javazhiyin/p/9851775.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值