I'm writing an HTTP POST request in Java using Apache HttpPost
and MultipartEntity
. In the data portion of the request, I am able to add simple parts using addPart(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":"noone@nowhere.com", "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("noone@nowhere.com"));
entity.addPart("properties", new ??? );
httpPost.setEntity(entity);
Thanks for your help!
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"));
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.
In the StringBody
pass a method that converts an array to json.
For example JSONArray
new JSONArray(collection).toString()
I was struggling with this too and was able to figure out the answer.
entity.addPart("properties[prop1]", new StringBody("123");
entity.addPart("properties[prop2]", new StringBody("abc");
For me, properties[]
or properties
did NOT work for me.
To specify number for each array works fine as below.
entity.addPart("properties[0]", new StringBody("value 1");
entity.addPart("properties[1]", new StringBody("value 2");
entity.addPart("properties[2]", new StringBody("value 3");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.