我有一个使用MultipartEntity内容类型将图像和文本作为HttpPost发送的方法。英语符号的一切都很好,但对于unicode符号(例如西里尔字母),它只发送???。因此,我想知道如何正确设置MultipartEntity的UTF-8编码,因为我已经尝试了So上建议的几种解决方案,但都不起作用。这里我已经有:
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我试着按照@Donaudampfschiffreizeitfahrt的建议使用InputStream。现在我���字符。
InputStream stream = new ByteArrayInputStream(mMessage.getBytes(Charset.forName("UTF-8")));
mpEntity.addBinaryBody("message", stream);
也尝试过:
mpEntity.addBinaryBody("message", mMessage.getBytes(Charset.forName("UTF-8")));
我用不同的方法解决了它,使用:
builder.addTextBody(key, שלום, ContentType.TEXT_PLAIN.withCharset("UTF-8"));
您可以使用下面的行在多部分实体中添加部件
entity.addPart("Data",新StringBody(Data,Charset.forName("UTF-8"));
在请求中发送unicode。
对于那些坚持这个问题的人,我就是这样解决的:
我调查了apachehttp组件库的源代码,发现了以下内容:
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;
因此,这似乎是apachelib中的某种bug/功能,它只允许将Content类型的头添加到MultipartEntity的一个部分,如果该部分的文件名不是null的话。所以我修改我的代码为:
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);
字符串部分出现了内容类型标头,符号现在已正确编码和解码。