0

I have an MultipartEntity declared like this:

MultipartEntity httpEnt = new MultipartEntity();
httpEnt.addPart("Test", new StringBody("test", ContentType.TEXT_PLAIN));

Then I make a rest call like this

HttpPost http = new HttPost(url);
HttpClient httpClient = HttpClients.createDefault();
http.setEntity(httpEnt);
httpClient.execute(http);

The MultipartyEntity seems to be deprecated and not working. I was considering using HttpEntity like this:

HttpEntity httpEnt = MultipartEntityBuilder.create().addPart("test", new StringBody(....)).build();

the problem with this is I want to add multiple parts in different methods and then later build. It seems like if I do it this way I will need to attach all parts at once and build in one line of code. Can I still use the deprecated one? A better way to do this?

Rajest Kahnna
  • 51
  • 1
  • 3
  • 6

1 Answers1

0

It seems like if I do it this way I will need to attach all parts at once and build in one line of code.

You don't need to do it all on one line. The MultipartEntityBuilder.create() call returns a builder object that you can assign to a variable, and then call methods on, one at a time as separate statements. Then finally call the build() method to get the HttpEntity.

(You don't have to use the "fluid" idiom in your code if you don't want to.)

Can I still use the deprecated one?

Yes (probably) ... but it is a good idea to move to the new way of building and representing the multi-part entity. At some point the deprecated API may be removed1, and that will cause version dependency problems for you, and/or people integrating or deploying your code with other things.

A better way to do this?

Yes. See above. (Though "better" in this context means more to your taste.)

Related (but not duplicate) Question:


1 - Unlike Sun / Oracle, the Apache HTTP Components folks often remove deprecated APIs after a period. Ignore deprecation warnings in 3rd-party libraries at your peril ...

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216