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

How to send body in restTemplate as application/x-www-form-urlencoded

可以在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"
                        }
                    ]
                },

代码:

        HttpHeaders headers = new HttpHeaders();
        headers.add(PostEnum.CONTENT_TYPE.getValue(), PostEnum.APPLICATION_URLENCODED.getValue());
        HttpEntity<?> requestEntity = new HttpEntity<>(gson.toJson(requestBody), headers);

邮递员截图:

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

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

  HttpHeaders headers = new HttpHeaders();
    headers.add(PostEnum.CONTENT_TYPE.getValue(), PostEnum.APPLICATION_URLENCODED.getValue());
    HttpEntity<?> requestEntity = new HttpEntity<>(requestBody, headers);