Spring의 RestTemplate으로 일반 웹 서버와 통신하는 예제이다. 한글 정보를 잘 받기 위해 StringHttpMessageConverter 을 잘 활용한다.
https://gist.github.com/knight1128/66f3e4817ab35c7397fd
package com.google.locationlab;
import com.google.common.collect.Lists;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.springframework.http.*;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
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 PortalRestTemplateIntegrationTest {
private Log logger = LogFactory.getLog(PortalRestTemplateIntegrationTest.class);
@Test
public void test() throws Exception {
RestTemplate restTemplate = new RestTemplate();
HttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
List<HttpMessageConverter<?>> httpMessageConverter = Lists.newArrayList();
httpMessageConverter.add(stringHttpMessageConverter);
restTemplate.setMessageConverters(httpMessageConverter);
URI targetUrl= UriComponentsBuilder.fromUriString("http://portal.net")
.path("search")
.queryParam("q", "잠실역")
.build()
.toUri();
HttpHeaders headers = new HttpHeaders();
Charset utf8 = Charset.forName("UTF-8");
MediaType mediaType = new MediaType("text", "html", utf8);
headers.setContentType(mediaType);
headers.set("User-Agent", "mozilla");
headers.set("Accept-Language", "ko");
// gzip 사용하면 byte[] 로 받아서, 압축을 풀고 decoding 해야 한다.
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(targetUrl.toURL().toString(), HttpMethod.GET, entity, String.class);
String result = responseEntity.getBody();
logger.info(result);
}
}
'general java' 카테고리의 다른 글
spring boot/loaded 애플리케이션 배포 방법 (0) | 2015.05.18 |
---|---|
FreeMarkerConfigurer : Cannot resolve template loader path [classpath:/templates/] to [java.io.File]: using SpringTemplateLoader as fallback (0) | 2015.05.18 |
[Spring] RestTemplate utf8 json 예제 (0) | 2015.05.15 |
[spring boot] Intellij 14.1 지원 (0) | 2015.05.13 |
[spring boot] application context xml import 하기 (0) | 2015.05.12 |