如何在java中将请求有效负载发送到REST API?

我想从以下位置检索 JSON 数据:https://git.eclipse.org/r/#/c/11376/

请求网址: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

任何人都可以帮我解决这个问题吗?

谢谢。


答案 1

以下代码适用于我。

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

}

答案 2

我尝试使用休息客户端。

头:

  • 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
  • 接受语言:空
  • 接受编码:gzip,deflate,sdch
  • 接受字符集:ISO-8859-1,utf-8;q=0.7,*;q=0.3
  • 内容类型:应用程序/json;字符集 = UTF-8
  • 内容长度: 73
  • 连接:保持活动状态

它工作正常。我用一个好的身体检索200 OK。

为什么要在请求中设置状态代码?和多个声明“Accept”与 Accept:application/json,application/json,application/jsonrequest。只要一句话就足够了。