MultipartEntityBuilder 和字符集

问题描述 投票:0回答:7

我升级了我的 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 中设置字符集,但现在已弃用,而且它似乎不起作用

java character-encoding
7个回答
23
投票

解决了:)事实证明 ContentType 现在很重要,我发送的是纯文本,还有一些 JSON 文本,

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

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

对于 JSON:

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

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


21
投票
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));

10
投票

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

builder.addTextBody(key, שלום, ContentType.TEXT_PLAIN.withCharset("UTF-8"));

2
投票

请尝试这个

UTF-8:

entity.addTextBody("your text", stringBuffer.toString(), ContentType.create("text/plain", Charset.forName("UTF-8")));

1
投票

就我而言,我首先像这样设置 contentType

ContentType contentType = ContentType.create(
                        HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);

添加对时,指定内容类型,如下所示

entityBuilder.addTextBody("title",pic.getTitle(),contentType);

如此处回答MultipartEntityBuilder 和 setCharset for UTF-8 发送空内容


0
投票

将 JSON 字符串更改为 BinaryUTF8 也是另一种有效的方法:

MultipartEntityBuilder meb = MultipartEntityBuilder.create();
meb.setCharset(java.nio.charset.StandardCharsets.UTF_8);
byte[] bytes = StringUtils.getBytesUtf8(some_text);
meb.addBinaryBody("JSON", bytes);

0
投票

我通过这种方式解决了它,使用:ContentType.TEXT_PLAIN.withCharset("UTF-8")。

                   MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
                    entityBuilder.addTextBody("operation", "postdita");
                    entityBuilder.addTextBody("path", fileNode.getPath(),ContentType.TEXT_PLAIN.withCharset("UTF-8"));
                    entityBuilder.addTextBody("createrev", "false");
                    entityBuilder.addBinaryBody("editorData", file);
                    entityBuilder.addTextBody("content-type", "application/x-www-form-urlencoded");
© www.soinside.com 2019 - 2024. All rights reserved.