Java Spring resttemplate character encoding

后端 未结 5 491
甜味超标
甜味超标 2020-12-05 10:29

I\'m using the Java Spring Resttemplate for getting a json via a get request. The JSON I\'m getting has instead of special character slike ü ö ä or ß some weird stuff. So I

相关标签:
5条回答
  • 2020-12-05 10:47

    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);
    
        }
    }
    
    0 讨论(0)
  • 2020-12-05 10:51

    I have solved this problem. I need to POST a string object in request body with UTF-8.

    text/plain

    httpHeaders.setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));

    applicaton/json

    httpHeaders.setContentType(new MediaType("applicaton", "json", StandardCharsets.UTF_8));

    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> resposeEntity = null;
    
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));
    
    HttpEntity<String> httpEntity = new HttpEntity<String>(stringContent, httpHeaders);
    responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, httpEntity, String.class);
    
    if (HttpStatus.OK.equals(responseEntity.getStatusCode())) {
        logger.debug("... success ... result: " + responseEntity.getBody());
    }
    
    0 讨论(0)
  • 2020-12-05 10:55

    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);
    
    0 讨论(0)
  • 2020-12-05 10:55

    You can still use String.class as a response type if you can do the following.

    Upgrading to spring-web 5.2 solves the problem. or set writeAcceptCharset property to false belongs to StringHttpMessageConverter and use that convertor further in RestTemplate instance.

    boolean writeAcceptCharSet = false;
    List<HttpMessageConverter<?>> c = restTemplate.getMessageConverters();
    for (HttpMessageConverter<?> mc : c) {
      if (mc instanceof StringHttpMessageConverter) {
        StringHttpMessageConverter mcc = (StringHttpMessageConverter) mc;
        mcc.setWriteAcceptCharset(writeAcceptCharSet);
      }
    }
    
    0 讨论(0)
  • 2020-12-05 11:02

    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);
    
    0 讨论(0)
提交回复
热议问题