[英]How to make HttpPut request with string array as body to it in JAVA?
我需要調用一個 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 主體只是一個字符串,因此只需將數組轉換為字符串(使用 Arrays.toString() 或任何其他方式)並使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.