简体   繁体   中英

force encoding http answer to utf-8

I'm using springframefork. I do get-request, but in server answer's header is not encoding information, but I know that it use UTF-8. How can I force encode answer body in UTF-8? This is not a web application - this is a simple java application.

public static void main(String[] args) {
    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "bearer ********");
    HttpEntity payload = new HttpEntity(headers);

    ResponseEntity<String> response = restTemplate.exchange("http://*******", HttpMethod.GET, payload, String.class);
    log.debug(response);
}

response is like

response = (org.springframework.http.ResponseEntity) <200 OK,{"id":228804,"field1":"ТеÑÑовÑй обÑекÑ","field2":"ТеÑÑÐ¾Ð²Ð°Ñ Ð¿ÑиÑина","field3":"ТеÑÑÐ¾Ð²Ð°Ñ Ð¿ÑиÑина","field4":221,"field5":null,"field6":"г.СанкÑ-ÐеÑеÑбÑÑг, 15-Ñ Ð»Ð¸Ð½Ð¸Ñ Ð.Ð., дом

etc

If you can edit web.xml, check this answer -> https://stackoverflow.com/a/5928162/6822933

Adding the CharacterEncodingFilter filter should solve your problem.

public static String strDecode(String str) throws UnsupportedEncodingException, CharacterCodingException {
    CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
    byte sByte[] = str.getBytes("iso-8859-1");
    ByteBuffer isoBuf = ByteBuffer.wrap(sByte);
    return utf8Decoder.decode(isoBuf).toString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM