我有一种使用HttpPost内容类型将图像和文本作为MultipartEntity发送的方法。对于英语符号,一切都很好,但是对于unicode符号(例如Cyrliics),它只发送?所以,我想知道如何为MultipartEntity正确设置UTF-8编码,因为我已经尝试过一些建议,但它们都没有工作。这是我已经拥有的:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.setCharset(Consts.UTF_8);
mpEntity.addPart("image", new FileBody(new File(attachmentUri), ContentType.APPLICATION_OCTET_STREAM));
ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
StringBody stringBody = new StringBody(mMessage, contentType);
mpEntity.addPart("message", stringBody);
final HttpEntity fileBody = mpEntity.build();
httpPost.setEntity(fileBody);
HttpResponse httpResponse = httpclient.execute(httpPost);UPD I试图使用InputStream作为@Donaudampfschifffreizeitfahrt的建议。现在我得到了���字符。
InputStream stream = new ByteArrayInputStream(mMessage.getBytes(Charset.forName("UTF-8")));
mpEntity.addBinaryBody("message", stream);也曾尝试过:
mpEntity.addBinaryBody("message", mMessage.getBytes(Charset.forName("UTF-8")));发布于 2014-09-16 13:36:32
对于那些坚持这个问题的人,我就是这样解决的:
我研究了apache组件库源代码,发现如下:
org.apache.http.entity.mime.HttpMultipart::doWriteTo()
case BROWSER_COMPATIBLE:
// Only write Content-Disposition
// Use content charset
final MinimalField cd = part.getHeader().getField(MIME.CONTENT_DISPOSITION);
writeField(cd, this.charset, out);
final String filename = part.getBody().getFilename();
if (filename != null) {
final MinimalField ct = part.getHeader().getField(MIME.CONTENT_TYPE);
writeField(ct, this.charset, out);
}
break;因此,它似乎是apache中的某种bug /特性,它只允许将内容类型的头添加到MultipartEntity的一个部分,如果这个部分具有非空文件名的话。因此,我将代码修改为:
Charset utf8 = Charset.forName("utf-8");
ContentType contentType = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), utf8);
ContentBody body = new ByteArrayBody(mMessage.getBytes(), contentType, "filename");
mpEntity.addPart("message", body);字符串部分出现内容类型标头,符号现在被正确编码和解码.
发布于 2016-10-07 14:22:34
我用另一种方法解决了这个问题,用:
builder.addTextBody(key, שלום, ContentType.TEXT_PLAIN.withCharset("UTF-8"));发布于 2017-01-03 07:22:43
您可以使用下面的行在多部分实体中添加部件。
Entity.addPart(“数据”,新StringBody(data,Charset.forName(“UTF-8”));
在请求中发送unicode。
https://stackoverflow.com/questions/25665178
复制相似问题