RestTemplate发送application/x-www-form-urlencoded格式的post请求

        在调用外部post接口时需要以 ? 带参数 的格式传递,拿postman测试后发现需要以x-www-form-urlencoded格式发送数据,所以选用RestTemplate的postForEntity方法,以下是代码示例

package org.springblade.test;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Map;

public class Test {

    @org.junit.jupiter.api.Test
    public void test() {
        RestTemplate restTemplate = new RestTemplate();

        //注意要使用MultiValueMap
        MultiValueMap paramsMap = new LinkedMultiValueMap<>();
        paramsMap.add("param1", "param1");
        paramsMap.add("param2", "param2");

        //设置请求信息
        RequestEntity requestEntity = RequestEntity
                .post("")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .accept(MediaType.ALL)
                .acceptCharset(StandardCharsets.UTF_8)
                .body(paramsMap);

        ResponseEntity mapResponseEntity = restTemplate.postForEntity("接口地址", requestEntity, String.class);
        
        //返回状态码
        HttpStatus statusCode = mapResponseEntity.getStatusCode();
        //返回数据
        String body = mapResponseEntity.getBody();
        Map map = JSON.parseObject(body, Map.class);
        Object stateCode = map.get("stateCode");
        Object message = map.get("message");
        Object resultStr = map.get("resultStr");

    }

}

参数请求类型

RestTemplate发送application/x-www-form-urlencoded格式的post请求_第1张图片

你可能感兴趣的:(Java,java)