简体   繁体   中英

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

It is possible to set "application/x-www-form-urlencoded" in HttpHeader, but I want to set for requestbody, could you please guide me?

sample 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"
                        }
                    ]
                },

code:

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

Postman screenshot: 在此处输入图像描述

Finally I found out that in "application/x-www-form-urlencoded" we have to use as following:

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM