Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MultipartEntityBuilder and Charset

Tags:

I upgraded my httpmime package, and now my strings are not sent or received as UTF-8

MultipartEntityBuilder entity = MultipartEntityBuilder.create(); Charset chars = Charset.forName("UTF-8"); entity.setCharset(chars); entity.addTextBody("some_text", some_text);  HttpPost httppost = new HttpPost(url);  httppost.setEntity(entity.build()); ...and so on.. 

what am I missing? I used to build a StringBody and set the charset in the stringbody, but that is deprecated now, and it just doesn't seem to work

like image 852
Amir.F Avatar asked Oct 10 '13 09:10

Amir.F


2 Answers

Solved it :) it turns out that ContentType is now important, and I was sending text that was plain, and also some text that was JSON,

for the plain text, you can use:

entity.addTextBody("plain_text",plain_text,ContentType.TEXT_PLAIN); 

and for JSON:

entity.addTextBody("json_text",json_text,ContentType.APPLICATION_JSON); 

that way the charset also works on JSON strings (weird, but now OK)

like image 169
Amir.F Avatar answered Dec 06 '22 12:12

Amir.F


entity.addTextBody("plain_text", plain_text); 

will use the default ContentType.TEXT_PLAIN which look like this...

public static final ContentType TEXT_PLAIN = ContentType.create("text/plain", Consts.ISO_8859_1); 

while ContentType.APPLICATION_JSON is using UTF-8 as below

public static final ContentType APPLICATION_JSON = ContentType.create("application/json", Consts.UTF_8); 

So what i did was create our own ContentType like this..

entity.addTextBody("plain_text", plain_text, ContentType.create("text/plain", MIME.UTF8_CHARSET)); 
like image 43
worawee.s Avatar answered Dec 06 '22 10:12

worawee.s