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.
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.
- How to post json data using Curl
- Spring Boot Get Cookie From Request
- Hibernate Query Language example
- Difference between save() and persist() in Hibernate
- Difference Between get() and load() in Hibernate
- Spring Boot Redis Cache Example
- JPA CriteriaBuilder example
- Orika Mapper Example
- Spring Boot JMS ActiveMQ Producer and Consumer Example
- Spring Boot Kafka Producer and Consumer Example – Step By Step Guide
- Spring Boot AWS SQS Listener Example