How do you add array in Data portion of Java HTTP POST request?
Solution 1
Here is one approach that works using StringEntity instead of MultipartEntity:
HttpPost httpPost = new HttpPost(newUrl);
String jsonData = <create using your favorite JSON library>;
StringEntity entity = new StringEntity(jsonData);
httpPost.setEntity(entity);
I would like to see an answer using MultipartEntity if there is one, but this will get the job done.
Solution 2
I did a similar thing as Roberg, but for me worked when I added []
to the end of the keys, like:
entity.addPart("properties[]", new StringBody("value 1"));
entity.addPart("properties[]", new StringBody("value 2"));
entity.addPart("properties[]", new StringBody("value 3"));
Solution 3
In the StringBody
pass a method that converts an array to json.
For example JSONArray
new JSONArray(collection).toString()
Blake Buckley
Updated on June 04, 2022Comments
-
Blake Buckley almost 2 years
I'm writing an HTTP POST request in Java using Apache
HttpPost
andMultipartEntity
. In the data portion of the request, I am able to add simple parts usingaddPart(name, StringBody)
. However, I need to add body part that is an array of values. How do I do this? The example from a curl request is:curl -k -H "Content-Type: application/json" --data '{ "name":"someName", "email":"[email protected]", "properties" : { "prop1" : "123", "prop2" : "abc" }}' -X POST 'https://some.place.com/api/test'
In Java, I can create the request like this, but I need to know how to create the "properties" array value since StringBody is for a single value:
HttpPost httpPost = new HttpPost(newAdultUrl); MultipartEntity entity = new MultipartEntity(); entity.addPart("name", new StringBody("someName")); entity.addPart("email", new StringBody("[email protected]")); entity.addPart("properties", new ??? ); httpPost.setEntity(entity);
Thanks for your help!
-
Viruzzo over 12 yearsYou should use a JSON library to do the encoding for you, it's much cleaner and flexible; a simple one is Gson.
-
Blake Buckley over 12 yearsOk, I have found one approach. I can use a StringEntity instead of a MultipartEntity and create my own JSON string from the various data fields required (we have used both Gson and json-simple in our stack). However, if someone knows of how to use the MultipartEntity approach from my code sample above I would still prefer that approach.
-
-
Blake Buckley over 12 yearsThat would pass the array as a String instead of an array. I need "properties" : {"key":"value"}, not "properties" : "{"key":"value"}".
-
Farmor over 12 yearstry creating an InputStream and use org.apache.http.entity.mime.content.InputStreamBody Actually I misunderstood your question and now I am only guessing