How to send post body using restTemplate as x-www-form-urlencoded

In this quick example, we will see how to send a post body in restTemplate as x-www-form-urlencoded with an example. Consider we have two parameters token and client_id that we want to send as post data as x-www-form-urlencoded. The token and client_id have some value as below.

Sending post body using restTemplate as x-www-form-urlencoded using postman

Let’s see an example to send post body using RestTemplate and x-www-form-urlencoded

import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Component
public class RestTemplateClient {

    @Value("${rest.client.url}")
    private String url;

    @Autowired
    private RestTemplate restTemplate;

    public ResponseEntity<JsonNode> callRestClient() {

        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.Jf36POk6yJV_adQssw5c";
        String clientId = "87ooooohhja22121hhahjrtyyysdddyyuu";
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("token", token);
        map.add("client_id", clientId);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> requestBodyFormUrlEncoded = new HttpEntity<>(map, headers);
        ResponseEntity<JsonNode> responseEntity = null;
        try {
            responseEntity = restTemplate.postForEntity(url, requestBodyFormUrlEncoded, JsonNode.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseEntity;
    }

}

  • In the above example, we are reading the rest URI using @Value annotation.
  • We have created a RestTemplate reference using @Autowired annotation.
  • We are using MultiValueMap and LinkedMultiValueMap for storing requested x-www-form-urlencoded.
  • We need to make sure we set x-www-form-urlencoded in headers.
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
  • We are using restTemplate.postForEntity() method
restTemplate.postForEntity(url, requestBodyFormUrlEncoded, JsonNode.class);

That’s all about How to send post body using restTemplate as x-www-form-urlencoded.

Other examples.