How to POST form data with Spring RestTemplate?
To POST form data with the RestTemplate class in Spring, you can use the postForObject method and pass it a URL, an object containing the form data, and the response type.
To POST form data with the RestTemplate class in Spring, you can use the postForObject method and pass it a URL, an HttpEntity containing the form data, and the response type.
Here's an example of how you can POST form data with RestTemplate:
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
public class Main {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
// create a map to store the form data
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.add("username", "john");
formData.add("password", "secret");
// set headers for form-encoded data
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(formData, headers);
// POST the form data to the server
String result = restTemplate.postForObject("http://example.com/login", request, String.class);
// print the result
System.out.println(result);
}
}This code creates a RestTemplate object and a MultiValueMap to store the form data. It then configures an HttpEntity with the APPLICATION_FORM_URLENCODED content type header to ensure the data is sent as form-encoded rather than JSON. The postForObject method sends the request and returns the server's response as a String, which is printed to the console.
Note that the postForObject method is just one of the several methods provided by RestTemplate for making HTTP requests. You can also use the postForEntity, postForLocation, or exchange methods, depending on your needs.
Note: RestTemplate has been deprecated since Spring 5.3. For new projects, the Spring team recommends using WebClient instead.