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

本文展示了如何使用Spring框架的RestTemplate进行x-www-form-urlencoded格式的POST请求,包括创建RequestEntity和处理响应内容。

        在调用外部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<String, String> 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<String> mapResponseEntity = restTemplate.postForEntity("接口地址", requestEntity, String.class);
        
        //返回状态码
        HttpStatus statusCode = mapResponseEntity.getStatusCode();
        //返回数据
        String body = mapResponseEntity.getBody();
        Map<String,Object> map = JSON.parseObject(body, Map.class);
        Object stateCode = map.get("stateCode");
        Object message = map.get("message");
        Object resultStr = map.get("resultStr");

    }

}

参数请求类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值