web-dev-qa-db-ja.com

要求ペイロードをREST JavaのAPIに送信するには?

次からJSONデータを取得したい: https://git.Eclipse.org/r/#/c/11376/

リクエストURL: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

誰かが私がこれを整理するのを助けることができますか?

ありがとう。

26
Gangaraju

次のコードは私のために動作します。

//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());
    }

}
39
Gangaraju

残りのクライアントで試しました。

ヘッダー:

  • POST/r/gerrit/rpc/ChangeDetailService HTTP/1.1
  • ホスト:git.Eclipse.org
  • ユーザーエージェント: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
  • コンテンツタイプ:application/json; charset = UTF-8
  • コンテンツの長さ:73
  • 接続:キープアライブ

正常に動作します。良い体で200 OKを取得します。

リクエストにステータスコードを設定するのはなぜですか?複数の宣言 "Accept" Accept:application/json、application/json、application/jsonrequest。文だけで十分です。

0
Calden