记一次RestTemplate使用x-www-form-urlencoded请求头进行提交

记一次RestTemplate使用x-www-form-urlencoded请求头进行提交

记录一次开发中遇到的问题:

post请求时目标接口数据格式为"application/x-www-form-urlencoded"

解决方案:
package cn.zack;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;

public class test {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        // 构建请求头信息
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-Type", "application/x-www-form-urlencoded");
        // 封装请求参数
        LinkedMultiValueMap<String, Object> linkedMultiValueMap = new LinkedMultiValueMap<>();
        linkedMultiValueMap.add("key", "value");
        // 构建请求体
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(linkedMultiValueMap, httpHeaders);
        // 发起http请求, 以字节流接收响应信息, 方便解码特殊的响应头(例如响应头为"Content-Language/zh-CN")
        byte[] bytes = restTemplate.postForObject("url", httpEntity, byte[].class);
        // u8解码
        try {
            String result = new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}