如何将restTemplate中的正文作为application/x-www-form-urlencoded发送

Toh*_*ari 3 java spring-boot spring-resttemplate

可以在HttpHeader中设置“application/x-www-form-urlencoded”,但我想为requestbody设置,你能指导一下吗?

示例 json:

                "header": [
                    {
                        "key": "Content-Type",
                        "value": "application/json",
                        "type": "text"
                    }
                ],
                "body": {
                    "mode": "urlencoded",
                    "urlencoded": [
                        {
                            "key": "username",
                            "value": "Tohid",
                            "type": "text"
                        },
                        {
                            "key": "password",
                            "value": "*mk",
                            "type": "text"
                        },
                        {
                            "key": "grant_type",
                            "value": "password",
                            "type": "text"
                        }
                    ]
                },
Run Code Online (Sandbox Code Playgroud)

代码 :

        HttpHeaders headers = new HttpHeaders();
        headers.add(MediaType.APPLICATION_JSON, APPLICATION_URLENCODED.getValue());
        HttpEntity<?> requestEntity = new HttpEntity<>(gson.toJson(requestBody), headers);
Run Code Online (Sandbox Code Playgroud)

邮递员截图: 在此输入图像描述

Toh*_*ari 6

最后我发现在“application/x-www-form-urlencoded”中我们必须使用以下内容:

 MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("username",propertyConfig.getUserName());

  HttpHeaders headers = new HttpHeaders();
    headers.add(MediaType.APPLICATION_JSON, "application/x-www-form-urlencoded");
    HttpEntity<?> requestEntity = new HttpEntity<>(requestBody, headers);
Run Code Online (Sandbox Code Playgroud)