问题描述
我需要调用rest api put方法,该方法接受一个参数Body(类型为arrray [string]),该参数将传递给“ BODY”而不是查询参数。
以下是此参数接受的值:
[
"string"
]
这些是我尝试拨打电话的步骤:
创建了一个用于对请求进行签名的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()或任何其他方式)并使用它即可。