0

我需要调用一个rest api put方法,该方法接受一个参数Body(类型为array [string]),该参数将传递给“BODY”而不是查询参数。

以下是此参数接受的值:

[
  "string"
]

api 接受的参数类型

这些是我尝试拨打电话的步骤:

创建了一个用于签署请求的 oauth 消费者对象和用于执行请求的 httpclient 对象

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

使用 json 创建 put 请求

 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);

执行请求获取响应码

  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");
     }

输出:

运行此程序时出现编译错误,因为字符串实体类不能接受字符串数组。是否有任何其他类可以接受 string[] 数组?

4

1 回答 1

0

正如评论中所讨论的,HTTP PUT 主体只是一个字符串,因此只需将数组转换为字符串(使用 Arrays.toString() 或任何其他方式)并使用它。

于 2020-10-14T14:03:23.500 回答