MultipartEntityBuilder和Charset
我升级了我的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..
我错过了什么? 我曾经构建一个StringBody并在stringbody中设置charset,但现在已经弃用了,它似乎不起作用
解决了它:)结果是ContentType现在很重要,我发送的文本很简单,还有一些JSON文本,
对于纯文本,您可以使用:
entity.addTextBody("plain_text",plain_text,ContentType.TEXT_PLAIN);
对于JSON:
entity.addTextBody("json_text",json_text,ContentType.APPLICATION_JSON);
这样charset也适用于JSON字符串(很奇怪,但现在还可以)
entity.addTextBody("plain_text", plain_text);
将使用默认的ContentType.TEXT_PLAIN,如下所示……
public static final ContentType TEXT_PLAIN = ContentType.create("text/plain", Consts.ISO_8859_1);
而ContentType.APPLICATION_JSON使用UTF-8,如下所示
public static final ContentType APPLICATION_JSON = ContentType.create("application/json", Consts.UTF_8);
所以我做的是像这样创建我们自己的ContentType ..
entity.addTextBody("plain_text", plain_text, ContentType.create("text/plain", MIME.UTF8_CHARSET));
对于那些说接受的解决方案对他们不起作用的人(它也不适合我),我用不同的方式解决了它,使用:
builder.addTextBody(key, שלום, ContentType.TEXT_PLAIN.withCharset("UTF-8"));
请试试这个
UTF-8:
entity.addTextBody("your text", stringBuffer.toString(), ContentType.create("text/plain", Charset.forName("UTF-8")));
在我的例子中,我首先像这样设置contentType
ContentType contentType = ContentType.create( HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
添加对时,请指定这样的内容类型
entityBuilder.addTextBody("title",pic.getTitle(),contentType);
正如这里所回答的, MultipartEntityBuilder和用于UTF-8的setCharset发送空内容