将JSON有效负载部署到服务器

时间:2014-04-03 04:37:04

标签: java json json-simple

我试图对需要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":"---"
}

1 个答案:

答案 0 :(得分:0)

发现我自己的愚蠢问题,有效负载没有将UUID写成字符串。

相关问题