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

Gan*_*aju 26 java rest httpurlconnection http-status-code-400

我想从以下内容中检索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
Run Code Online (Sandbox Code Playgroud)

请求有效负载:

{"jsonrpc":"2.0","method":"changeDetail","params":[{"id":11376}],"id":1}
Run Code Online (Sandbox Code Playgroud)

我已经尝试过这个答案,但我得到了400 BAD REQUEST.

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

谢谢.

Gan*_*aju 40

以下代码适用于我.

//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);
Run Code Online (Sandbox Code Playgroud)

方法实现:

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

}
Run Code Online (Sandbox Code Playgroud)

  • BufferedWriter在这里略显过分.此外,如果您发送UTF-8字符,您将遇到麻烦.你应该使用`OutputStreamWriter writer = new OutputStreamWriter(os,"UTF-8");`. (2认同)