简体   繁体   中英

Java REST api Send array using HTTP PUT method

I'm not able to implement an REST API in Java

I've got a working example of a generic implementation using PHP.

How I can implement it in Java using json library and HttpClient (HttpPut request) ?

Here it is the PHP example

//DATA TO UPDATE
$postData = array(
    'item'   => array(
        'title'              => 'My title',
        'personal_reference' => 'My personal ref',
        'qty'                => 3,
        'description'        => 'My description'
    )
);


//RESOURCE CALL WITH PUT METHOD
$url = 'https://rest.restserv.com/item/1234?token=MyPersonalToken';
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POSTFIELDS, http_build_query($postData) );
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$xml_response  = curl_exec($ch);

My (not working) approach was this:

Map<String,String> dataMap = new HashMap<String,String>();
dataMap.put("title", "some text");
dataMap.put("personal_reference", "my ref");
dataMap.put("qty", "1");
dataMap.put("description", "some desciption text");

String url = "https://rest.restserv.com/item/1234?token=MyPersonalToken";

HttpPut putRequest = new HttpPut(url);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (Map.Entry<String, String> entry : dataMap.entrySet()) {
    builder.addTextBody(entry.getKey(), entry.getValue());
}
putRequest.setEntity(builder.build());
response = httpClient.execute(putRequest);

thanks and best regards.

UPDATE

Now I'm trying with this other approach. The object Map<String,String> dataMap contains all the details of the item to send. Unfortunately i'm still not able to send item details. The request status is 200 and also the response is ok.

HttpClient httpClient = HttpClientBuilder.create().build();
HttpPut putRequest = new HttpPut(url);
putRequest.addHeader("Content-Type", "application/json; charset=utf-8");
JSONArray itemDetails = new JSONArray();                
itemDetails.put(dataMap);               
JSONObject root = new JSONObject().put("item", itemDetails);
StringEntity entity = new StringEntity(root.toString(2),  "UTF-8");
System.out.println("ROOT is:::: "+root.toString(2));
putRequest.setEntity(entity);
response = httpClient.execute(putRequest);

root.toString(2) result is:

{"item": [{"title": "My title","personal_reference": "My personal ref","qty": "3","description": "My description"}]}

PROBLEM

It seems that payload wasn't correctly formatted and were skipped by the REST server.

SOLUTION

The problem has been solved using kong.unirest.Unirest library.

Bye

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM