Tohid Makari
Tohid Makari

Reputation: 2484

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(MediaType.APPLICATION_JSON, APPLICATION_URLENCODED.getValue());
        HttpEntity<?> requestEntity = new HttpEntity<>(gson.toJson(requestBody), headers);

Postman screenshot : enter image description here

Upvotes: 4

Views: 11799

Answers (1)

Tohid Makari
Tohid Makari

Reputation: 2484

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(MediaType.APPLICATION_JSON, "application/x-www-form-urlencoded");
    HttpEntity<?> requestEntity = new HttpEntity<>(requestBody, headers);

Upvotes: 9

Related Questions