类型 MultipartEntity 已被弃用。

53

文档显示org.apache.http.entity.mime.MultipartEntity类已被弃用。请问有没有人能够推荐替代方案?

我在我的代码中使用它如下:

entity.addPart("params", new StringBody("{\"auth\":{\"key\":\""
            + authKey + "\"},\"template_id\":\"" + templateId + "\"}"));
entity.addPart("my_file", new FileBody(image));
httppost.setEntity(entity);
2个回答

118

如果你仔细阅读文档,你会注意到应该使用MultipartEntityBuilder作为替代方案。

例如:

MultipartEntityBuilder builder = MultipartEntityBuilder.create();        

/* example for setting a HttpMultipartMode */
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

/* example for adding an image part */
FileBody fileBody = new FileBody(new File(image)); //image should be a String
builder.addPart("my_file", fileBody); 
//and so on
请注意,FileBody类有几个构造函数,您可以通过这些构造函数提供mimeTypecontent type等参数。
在向构建器传递build instructions后,通过调用MultipartEntityBuilder#build()方法,您可以获取已构建的HttpEntity
HttpEntity entity = builder.build();

1
我可以问一下,当我将图像作为MultipartFile发布时,我是否应该设置httppost的标头,例如httppost.setheader("Content-Type", "multipart/form-data;boundary=" + boundary)? - Mycoola
5
现在,随着API 23的到来,MultipartEntityBuilder不再是Android的一部分。在这种情况下如何处理multipart/form-data? - webo80
2
@kocko 谢谢你的回复,但是对我并没有帮助,它只是提供了一些指导方针,而不是太多技术层面的内容。 - webo80
1
HttpEntity现在也已经被弃用了。所以不能使用builder.build()。有什么替代方案吗? - Ankur Raiyani
1
我无法执行。错误为**'addPart(org.apache.http.entity.mime.FormBodyPart)'不是'org.apache.http.entity.mime.MultipartEntityBuilder'中的公共方法,因此无法从包外进行访问**。 - Lei Yang
显示剩余8条评论

6

我仍然看到很多教程仍在使用已弃用的API,这也是我写这篇文章的原因。为了便于未来的访问者(直到该API被弃用为止;))

File image = "...."; 
FileBody fileBody = new FileBody(image);
MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                         .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                         .addTextBody("params", "{....}")
                         .addPart("my_file", fileBody);
HttpEntity multiPartEntity = builder.build();

String url = "....";
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(multiPartEntity);
...

3
HttpEntity已经过时。 - Gary Davies
它只是针对Android SDK已被弃用,但在其他任何地方使用仍然完全正常。org.apache.commons.HttpEntity并未被弃用。 - liltitus27
addTextBodyaddPart有什么区别? - Lei Yang
addPart是私有的。 - Trevor Hart
@TrevorHart,截至最新版本4.5.6addPart仍然是公共API,请参见最新的API文档 - Neo
可能是我使用的版本问题,我会调查一下。 - Trevor Hart

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接