Search code examples
javaapachehttp-postmultipart

How do you add array in Data portion of Java HTTP POST request?


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":"[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!


Solution

  • 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.