Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
rest template with object mapping example code in utf8 communication
package com.google.locationlab;
import com.google.common.collect.Lists;
import com.google.locationlab.model.LocationResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.List;
public class RestTemplateIntegrationTest {
private Log logger = LogFactory.getLog(RestTemplateIntegrationTest.class);
@Test
public void test() throws Exception {
RestTemplate restTemplate = new RestTemplate();
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
HttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
List<HttpMessageConverter<?>> httpMessageConverter = Lists.newArrayList();
httpMessageConverter.add(mappingJackson2HttpMessageConverter);
httpMessageConverter.add(stringHttpMessageConverter);
restTemplate.setMessageConverters(httpMessageConverter);
URI targetUrl= UriComponentsBuilder.fromUriString("http://location-api.google.com")
.path("search")
.queryParam("text", "잠실역")
.build()
.toUri();
HttpHeaders headers = new HttpHeaders();
Charset utf8 = Charset.forName("UTF-8");
MediaType mediaType = new MediaType("application", "json", utf8);
headers.setContentType(mediaType);
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ParameterizedTypeReference<List<LocationResponse>> responseType = new ParameterizedTypeReference<List<LocationResponse>>() { };
ResponseEntity<List<LocationResponse>> responseEntity = restTemplate.exchange(targetUrl.toURL().toString(), HttpMethod.GET, entity, responseType);
List<LocationResponse> result = responseEntity.getBody();
logger.info(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment