我有一个使用MultipartEntity内容类型将图像和文本作为HttpPost发送的方法。一切都很适合英文符号,但对于unicode符号(例如Cyrliics),它只发送???。所以,我想知道,如何正确地为MultipartEntity设置UTF-8编码,因为我已经尝试了几个在SO上建议的解决方案,但没有一个能够工作。 这里我已经:通过MultipartEntity发送Unicode字符
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 我试图用的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")));
您正在使用'默认字符集'进行IO操作,无论您是使用什么操作。这是来自Sun的一个糟糕的设计,你必须**总是**使用OutputStreamReader/InputStreamWriter与指定的编码,如果你处理写/读字符串。 – 2014-09-04 12:15:22
@Donaudampfschifffreizeitfahrt您好!你能更具体一点,我怎么能在我的问题的上下文中使用InputStreamWriter?示例将不胜感激。谢谢。 – mol 2014-09-04 12:34:55
呵呵,应该是OutputStreamWriter和InputStreamReader。 httpclient必须具有Body类型接受Writer,但我现在没有该库。只需搜索这些类名称即可。 – 2014-09-04 12:39:18