How to make HttpPut request with string array as body to it in JAVA?

2.5k views Asked by At

I have a requirement to call a rest api put method which accepts one parameter Body(of type arrray[string]) which is to be passed to "BODY" not query parameter.

Below is the value that this parameter accepts:

[
  "string"
]

Type of parameter that api accepts

These are the steps that I tried to make the call:

created an oauth consumer object that is used to sign the request and httpclient object to execute the request

  consumer = new CommonsHttpOAuthConsumer("abc", "def");
  requestConfig = RequestConfig.custom().setConnectTimeout(300 * 1000).build();
  httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

Creating the put request with json

 URL url = new URL("http://www.example.com/resource");
 String[] dfNames = {};
 dfNames[0] = "test";
 putreq = new HttpPut(url);
 putreq.setHeader("Id","xyz");
 StringEntity input = new StringEntity(dfNames);  //Getting compilation error
 input.setContentType("application/json");
 putreq.setEntity(input);

Executing the request to get the response code

  updateresponse = httpClient.execute(putreq);
  int updatehttpResponseCode = updateresponse.getStatusLine().getStatusCode();
  System.out.println("post Response Code :: " + updatehttpResponseCode);
  if (updatehttpResponseCode == 200) 
    { 
     System.out.println("PuT request worked);
    } 
  else 
     {
     System.out.println("PuT request not worked");
     }

OUTPUT:

I am getting a compilation error when running this since the string entity class cannot accept string array. Is there any other class which will accept the string[] array?

1

There are 1 answers

0
The Student On BEST ANSWER

As discussed in the comments, the HTTP PUT body is just a string, so just convert the array to String (with Arrays.toString() or any other way) and use it.