In Spring framework RestTemplate is very useful in terms of sending various http requests to RESTful resources and this post shows simple examples on how to set Content-Type, Accept headers, as well as the content encoding, which is especially important when requesting with non-ascii (e.g. CJK languages) data.

Initialize RestTemplate

import java.nio.Charset;
import java.util.Arrays;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import com.fasterxml.jackson.databind.ObjectMapper;

RestTemplate restTemplate = new RestTemplate();

Set Content-Type

HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);

Set Accept

headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setAcceptCharset(Arrays.asList(Charset.forName("UTF-8")));

Set encoding - option 1

restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));

Set encoding - option 2

MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
httpHeaders.setContentType(mediaType);

Post request

XObject xObject = new XObject();
xObject.setFieldA("a");
xObject.setFieldB("b");
ObjectMapper objectMapper = new ObjectMapper();
String payload = objectMapper.writeValueAsString(xObject);
HttpEntity<String> httpEntity = new HttpEntity<String>(payload, httpHeaders);
YObject yObject = restTemplate.postForObject(httpUrl, httpEntity, YObject.class);

References

BACK TO TOP
Post tagged with: spring, java