java 为多部分实体设置编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5791508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:46:34  来源:igfitidea点击:

Setting encoding for a Multipart Entity

javaandroidmultipartentity

提问by Alex

I want to set a UTF-8 Encoding to a MultipartEntity object or to StringBody object. Is there any way to do it? I know how to set the Charset but not the Encoding.

我想将 UTF-8 编码设置为 MultipartEntity 对象或 StringBody 对象。有什么办法吗?我知道如何设置字符集但不知道如何设置编码。

Thank you.

谢谢你。

回答by Paul Burke

This is from an anddev.org post at this link, but is currently down, so I have pasted the snippet below. I haven't tried this code, but I hope it helps.

这是来自此链接上的 anddev.org 帖子,但目前已关闭,因此我粘贴了下面的代码段。我没有试过这个代码,但我希望它有帮助。

MultipartEntity multipart = new MultipartEntity();
File file = new File("/filepath");  // File with some location (filepath)
Charset chars = Charset.forName("UTF-8"); // Setting up the encoding
FileBody fileB = new FileBody(file); // Create a new FileBody with the above mentioned file
multipart.addPart("data", fileB); // Add the part to my MultipartEntity. "data" is parameter name for the file
StringBody stringB;  // Now lets add some extra information in a StringBody
try {
    stringB = new StringBody("I am the caption of the file",chars);  // Adding the content to the StringBody and setting up the encoding
    multipart.addPart("caption", stringB); // Add the part to my MultipartEntity
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

HttpPost post = new HttpPost(url); // Setting up a HTTP Post method with the target url
post.setEntity(multipart); // Setting the multipart Entity to the post method
HttpResponse resp = client.execute(post);  // Using some HttpClient (I'm using DefaultHttpClient) to execute the post method and receive the response

回答by Krystian

Method, which is above is deprecated.

不推荐使用上述方法。

There is answer which is made in correct way now. MultipartEntityBuilder and Charset

现在有正确的回答。 MultipartEntityBuilder 和字符集