The type MultipartEntity is deprecated

JavaApache

Java Problem Overview


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

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);

Java Solutions


Solution 1 - Java

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

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 FileBody class, by which you can provide mimeType, content type, etc.

After you're done with passing build instructions to the builder, you can get the built HttpEntity by invoking the MultipartEntityBuilder#build() method:

HttpEntity entity = builder.build();

Solution 2 - Java

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 ;) )

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);
...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnullUserView Question on Stackoverflow
Solution 1 - JavaKonstantin YovkovView Answer on Stackoverflow
Solution 2 - JavaNeoView Answer on Stackoverflow