How to POST form data with Spring RestTemplate?

sim :

I want to convert the following (working) curl snippet to a RestTemplate call:

curl -i -X POST -d "[email protected]" https://app.example.com/hr/email

How do I pass the email parameter correctly? The following code results in a 404 Not Found response:

String url = "https://app.example.com/hr/email";

Map<String, String> params = new HashMap<String, String>();
params.put("email", "[email protected]");

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity( url, params, String.class );

I've tried to formulate the correct call in PostMan, and I can get it working correctly by specifying the email parameter as a "form-data" parameter in the body. What is the correct way to achieve this functionality in a RestTemplate?

Tharsan Sivakumar :

The POST method should be sent along the HTTP request object. And the request may contain either of HTTP header or HTTP body or both.

Hence let's create an HTTP entity and send the headers and parameter in body.

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

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#postForObject-java.lang.String-java.lang.Object-java.lang.Class-java.lang.Object...-

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=418916&siteId=1