Domanda

I'm attempting to make an API call to a server that requires a JSON payload, and returns one as well.

//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() returns a JSONObject that I want to send on the web request, however the server returns a 400 HTTP status error indicating that something I set must have been wrong.

How can I properly output/POST a JSONObject to the web server?

Resources:

Example payload:

{
    "agent": {
        "name":"Minecraft",
        "version":1
    },
    "password":"---",
    "clientToken":cf6ffbc6-a681-47c1-9999-119c6d2ed597,
    "username":"---"
}
È stato utile?

Soluzione

Found my own silly issue, the payload wasn't writing the UUID as a string.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top