Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell RestTemplate to POST with UTF-8 encoding?

I'm having problems posting JSON with UTF-8 encoding using RestTemplate. Default encoding for JSON is UTF-8 so the media type shouldn't even contain the charset. I have tried to put charset in the MediaType but it doesn't seem to work anyway.

My code:

String dataJson = "{\"food\": \"smörrebröd\"}"; HttpHeaders headers = new HttpHeaders(); MediaType mediaType = new MediaType("application", "json", StandardCharsets.UTF_8); headers.setContentType(mediaType);  HttpEntity<String> entity = new HttpEntity<String>(dataJson, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<Boolean> formEntity = restTemplate.exchange(postUrl, HttpMethod.POST, entity, Boolean.class); 
like image 583
anssias Avatar asked Apr 01 '15 13:04

anssias


People also ask

How do I change my encoding to UTF-8?

UTF-8 Encoding in Notepad (Windows)Click File in the top-left corner of your screen. In the dialog which appears, select the following options: In the "Save as type" drop-down, select All Files. In the "Encoding" drop-down, select UTF-8.

Is UTF-8 the default encoding?

Fortunately UTF-8 is the default per sé. When reading an XML document and writing it in another encoding, mostly this attribute will be patched too.

Is UTF-8 character set or encoding?

The Difference Between Unicode and UTF-8 Unicode is a character set. UTF-8 is encoding. Unicode is a list of characters with unique decimal numbers (code points). A = 65, B = 66, C = 67, ....

Is UTF-8 same as UTF-8?

UTF-8 is a valid IANA character set name, whereas utf8 is not. It's not even a valid alias. it refers to an implementation-provided locale, where settings of language, territory, and codeset are implementation-defined.


1 Answers

You need to add StringHttpMessageConverter to rest template's message converter with charset UTF-8. Like this

RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters()         .add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8)); 
like image 185
mushfek0001 Avatar answered Oct 13 '22 10:10

mushfek0001