Java 不推荐使用 MultipartEntity 类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19196292/
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-08-12 14:57:07  来源:igfitidea点击:

The type MultipartEntity is deprecated

javaapache

提问by Syam S

The documentation says the org.apache.http.entity.mime.MultipartEntityclass is deprecated. Could anybody please suggest me an alternative ?

文档说org.apache.http.entity.mime.MultipartEntity该类已被弃用。有人可以给我建议一个替代方案吗?

I am using this in my code like this:

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

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

采纳答案by Konstantin Yovkov

If you read the docs carefully, you'll notice that you should use MultipartEntityBuilderas an alternative.

如果您仔细阅读文档,您会注意到您应该将其MultipartEntityBuilder用作替代方案。

For example:

例如:

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

Note that there are several constructors for the FileBodyclass, by which you can provide mimeType, content type, etc.

请注意,FileBody该类有多个构造函数,您可以通过它们提供mimeTypecontent type等。

After you're done with passing build instructionsto the builder, you can get the built HttpEntityby invoking the MultipartEntityBuilder#build()method:

完成将构建指令传递给构建器后,您可以HttpEntity通过调用该MultipartEntityBuilder#build()方法来获取构建:

HttpEntity entity = builder.build();

回答by Neo

I still see so many tutorials still using the deprecated APIs which is what lead me to this post. For the benefit of future visitors (until this API gets deprecated ;) )

我仍然看到很多教程仍在使用已弃用的 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);
...