我想将 UTF-8 编码设置为 MultipartEntity 对象或 StringBody 对象。有什么办法吗?我知道如何设置字符集但不知道编码。
谢谢你。
我想将 UTF-8 编码设置为 MultipartEntity 对象或 StringBody 对象。有什么办法吗?我知道如何设置字符集但不知道编码。
谢谢你。
这是来自此链接上的 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
不推荐使用上面的方法。
现在有正确的回答。 MultipartEntityBuilder 和 Charset