[英]How to send Request payload to REST API in java?
我想從以下內容中檢索JSON數據: https : //git.eclipse.org/r/#/c/11376/
請求URL: https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService
: https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService
請求方法: POST
請求標題:
Accept:application/json
Content-Type:application/json; charset=UTF-8
請求有效負載:
{"jsonrpc":"2.0","method":"changeDetail","params":[{"id":11376}],"id":1}
我已經嘗試過這個答案,但我得到了400 BAD REQUEST
。
任何人都可以幫我解決這個問題嗎?
謝謝。
以下代碼適用於我。
//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);
方法實現:
public static String sendPostRequest(String requestUrl, String payload) {
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
return jsonString.toString();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
我嘗試了一個休息客戶端。
標題:
它工作正常。 我用一個好身體檢索200 OK。
為什么在請求中設置狀態代碼? 使用Accept:application / json,application / json,application / jsonrequest進行多次聲明“ Accept ”。 只是一個聲明就足夠了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.