簡體   English   中英

如何將請求有效負載發送到Java中的REST API?

[英]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/ChangeDetailServicehttps://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());
    }

}

我嘗試了一個休息客戶端。

標題:

  • POST / r / gerrit / rpc / ChangeDetailService HTTP / 1.1
  • 主持人:git.eclipse.org
  • User-Agent:Mozilla / 5.0(Windows NT 5.1; rv:18.0)Gecko / 20100101 Firefox / 18.0
  • 接受:application / json
  • Accept-Language:null
  • Accept-Encoding:gzip,deflate,sdch
  • accept-charset:ISO-8859-1,utf-8; q = 0.7,*; q = 0.3
  • Content-Type:application / json; 字符集= UTF-8
  • 內容長度:73
  • 連接:保持活力

它工作正常。 我用一個好身體檢索200 OK。

為什么在請求中設置狀態代碼? 使用Accept:application / json,application / json,application / jsonrequest進行多次聲明“ Accept ”。 只是一個聲明就足夠了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM