MultipartEntityBuilder和Charset

Ami*_*r.F 20 java character-encoding

我升级了我的httpmime包,现在我的字符串没有作为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..
Run Code Online (Sandbox Code Playgroud)

我错过了什么?我曾经构建一个StringBody并在stringbody中设置charset,但现在已经弃用了,它似乎不起作用

Ami*_*r.F 23

解决了它:)结果是ContentType现在很重要,我发送的文本很简单,还有一些JSON文本,

对于纯文本,您可以使用:

entity.addTextBody("plain_text",plain_text,ContentType.TEXT_PLAIN);
Run Code Online (Sandbox Code Playgroud)

对于JSON:

entity.addTextBody("json_text",json_text,ContentType.APPLICATION_JSON);
Run Code Online (Sandbox Code Playgroud)

这样charset也适用于JSON字符串(很奇怪,但现在还可以)


小智 17

entity.addTextBody("plain_text", plain_text);
Run Code Online (Sandbox Code Playgroud)

将使用默认的ContentType.TEXT_PLAIN,它看起来像这样......

public static final ContentType TEXT_PLAIN = ContentType.create("text/plain", Consts.ISO_8859_1);
Run Code Online (Sandbox Code Playgroud)

而ContentType.APPLICATION_JSON使用UTF-8,如下所示

public static final ContentType APPLICATION_JSON = ContentType.create("application/json", Consts.UTF_8);
Run Code Online (Sandbox Code Playgroud)

所以我所做的就是像这样创建我们自己的ContentType.

entity.addTextBody("plain_text", plain_text, ContentType.create("text/plain", MIME.UTF8_CHARSET));
Run Code Online (Sandbox Code Playgroud)


Nom*_*fan 7

对于那些说接受的解决方案对他们不起作用的人(它也不适合我),我用不同的方式解决了它,使用:

builder.addTextBody(key, ????, ContentType.TEXT_PLAIN.withCharset("UTF-8"));
Run Code Online (Sandbox Code Playgroud)