设置Multipart Entity的编码

时间:2011-04-26 14:03:10

标签: java android multipartentity

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

谢谢。

2 个答案:

答案 0 :(得分:37)

这是来自this link的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

答案 1 :(得分:0)

上面的方法已被弃用。

现在有正确的答案。 MultipartEntityBuilder and Charset