0

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":"---"
}
Rogue
  • 11,105
  • 5
  • 45
  • 71
  • And HTTP error code `400` means **bad request**, which is extremely generic... don't you have any more information about what's wrong about your request? In my opinion, you're actually sending a JSON payload and the server should understand that this indeed is a JSON payload. If it wasn't the case, I would expect the server to return an HTTP error `415`, for **Unsupported media type** – ccjmne Apr 03 '14 at 04:42
  • @ccjmne So you see nothing inherently wrong with the code then? `400` really is generic, so I'm not entire certain about what is wrong. I'll add a link about the protocol, I forgot to include that originally. – Rogue Apr 03 '14 at 04:44

1 Answers1

0

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

Rogue
  • 11,105
  • 5
  • 45
  • 71