Java Spring resttemplate character encoding
First I tried @beerbajay 's way , but it not helpsã Finally I resolve it by below way
RestTemplate template = new RestTemplate();
// template.getMessageConverters()
// .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
HttpHeaders headers = new HttpHeaders();
headers.setAccept(newArrayList(MediaType.APPLICATION_JSON));
ResponseEntity<String> response = template.exchange(url, HttpMethod.GET, new HttpEntity<String>(headers), String.class);
I've same issue on this case, after one search, I've got this link: https://gist.github.com/knight1128/66f3e4817ab35c7397fd
its workaround is working for me:
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);
}
}
You just need to add the StringHttpMessageConverter
to the template's message converters:
RestTemplate template = new RestTemplate();
template.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
ResponseEntity<Object> response = template.exchange(endpoint, method, entity,
Object.class);