如何在JAVA中以字符串数组为主体进行HttpPut请求?

问题描述

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

以下是此参数接受的值:

[
  "string"
]

Type of parameter that api accepts

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

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

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

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

执行请求以获取响应代码

  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 []数组的类吗?

解决方法

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...