我正在尝试对需要 JSON 有效负载的服务器进行 API 调用,并返回一个。
//Prereq: username/password are string variables, this.url is a URL()
HttpURLConnection http = (HttpURLConnection) this.url.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "application/json");
http.setUseCaches(false);
http.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(http.getOutputStream())) {
wr.writeBytes(this.getPayload(username, password).toJSONString());
wr.flush();
}
StringBuilder sb = new StringBuilder();
//Error here - returned 400.
try (InputStreamReader is = new InputStreamReader(http.getInputStream()); BufferedReader br = new BufferedReader(is)) {
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
JSONObject response = (JSONObject) JSONValue.parse(sb.toString());
getPayload()
返回一个我想在 Web 请求上发送的 JSONObject,但是服务器返回一个400
HTTP 状态错误,表明我设置的东西一定是错误的。
如何正确地POST
将 JSONObject 输出/到 Web 服务器?
资源:
有效载荷示例:
{
"agent": {
"name":"Minecraft",
"version":1
},
"password":"---",
"clientToken":cf6ffbc6-a681-47c1-9999-119c6d2ed597,
"username":"---"
}