Spring RestTemplate을 사용하는 예제이다. 


API 서버와 json 통신(utf)을 하는 예제로서, 결과 값을 List<Object>로 변환하는 예제이다. 


한글 정보를 잘 받기 위해 StringHttpMessageConverter 을 잘 활용한다. 한글 깨짐없이 문제 없이 동작한다. 



https://gist.github.com/knight1128/b0e545a03e2d066da8f6#file-resttemplateintegrationtest


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); } }



Posted by '김용환'
,