0

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?

Revaix
  • 15
  • 5
  • You are using a `StringEntity`with a single string as source, how should that be sent as an array? Also, all this oauth stuff has nothing to do with your problem and you don't have a minimal reproducible example, only code snippets. – Smutje Oct 07 '20 at 08:15
  • @Smutje I have removed the unnecessary oauth stuff and I am looking for any other class which can accept array[string] . – Revaix Oct 07 '20 at 08:34
  • Isn't the body, itself, just a string? Decide which separator you want to use, and write the array as a single string. – The Student Oct 07 '20 at 13:31
  • @TomBrito Thanks man. I converted the array to string using Arrays.toString() and then I passed the string to string entity. It worked. – Revaix Oct 10 '20 at 06:05

1 Answers1

0

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.

The Student
  • 27,520
  • 68
  • 161
  • 264