gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:18:39 25 4
gpt4 key购买 nike

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

请求网址:https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService

请求方法:POST

请求 header :

Accept:application/json

Content-Type:application/json; charset=UTF-8

请求负载:

{"jsonrpc":"2.0","method":"changeDetail","params":[{"id":11376}],"id":1}

我已经尝试过 this answer 但我收到 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());
}

}

关于java - java - 如何在Java中将请求有效负载发送到REST API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15570656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com