Explain Codes LogoExplain Codes Logo

How to POST form data with Spring RestTemplate?

java
resttemplate
http-method
file-upload
Anton ShumikhinbyAnton Shumikhin·Aug 7, 2024
TLDR

Here is a quick way to POST form data using Spring RestTemplate:

RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // Content-Type: application/x-www-form-urlencoded MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("field1", "value1"); // Keys and values, similar process as filling up a form formData.add("field2", "value2"); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers); ResponseEntity<String> response = restTemplate.postForEntity("http://target-url.com/submit", requestEntity , String.class); // Fire away!

This quick guide sets the content type to APPLICATION_FORM_URLENCODED, packs the form data, and sends off a POST request.

Making fine-tuned requests using Exchange method

For those craving for more control over the HTTP requests, there are more details you can configure:

ResponseEntity<String> response = restTemplate.exchange( "http://target-url.com/submit", HttpMethod.POST, requestEntity, String.class); // Remember to make sure your URL is correct (#protip)

POSTing multipart/form-data

When dealing with file uploads, just switch your MediaType and MultiValueMap:

headers.setContentType(MediaType.MULTIPART_FORM_DATA); // Changing the media type for file upload MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add("file", new FileSystemResource("/path/to/file")); // Just proves how much 'path-to' things we programmers have to deal with HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

Remember: Choose the right MediaType for the occasion!

Error management and awesome logging

RestTemplate is no 'SilentBob'. It's quite vocal about issues:

  • Client messing up? HttpClientErrorException to the rescue.
  • Server goofed up? HttpServerErrorException has your back.
  • I/O messing with your groove? ResourceAccessException lets you know.

RestTemplate mocking for tests

For those who like to be in complete control of their test environment:

MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate); mockServer.expect(ExpectedCount.once(), requestTo("http://target-url.com/submit")) .andExpect(method(HttpMethod.POST)) .andRespond(withSuccess("response body", MediaType.APPLICATION_JSON)); // But remember, with great mocking, comes great responsibility!

Casting reprieve with Generics

Casting can be tiresome, generics can give you a break:

ResponseEntity<MyResponseType> response = restTemplate.postForEntity( "http://target-url.com/submit", requestEntity, MyResponseType.class); // Generics totally dig polymorphism, just 'classier'