0

Trying to make a JSON POST request using HttpURLConnection, the code that's constructing the JSONObject and writing it to the output stream is here:

            Iterator dataload = data.entrySet().iterator();
            JSONObject sendData = new JSONObject();
            while (dataload.hasNext()) {
                thisEntry = (Entry) dataload.next();
                Object key = thisEntry.getKey();
                Object value = thisEntry.getValue();
                sendData.put(key.toString(), value.toString());
            }


            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8;");
            connection.setUseCaches (false);

            OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
            wr.write(sendData.toString());
            wr.flush();
            wr.close();

This shows up in wireshark like this:

https://i.stack.imgur.com/R0tOr.png (can't post images, not enough reputation)

As you can see, the content is being put in the "Line-based text data" field, and not the JSON field, which is present but empty.

Can anyone tell me why this is happening?

boiiocks
  • 3
  • 3
  • It looks like you are serializing a JSON object to a string before it hits the wire. Isn't there some kind of JSON writer that will serialize the JSON object as JSON instead? – Kode Charlie Apr 11 '14 at 21:31
  • Just a suggestion: the OutputStreamWriter could have the wrong (charset conversion) effect, try replacing it with `OutputStream out = connection.getOutputStream(); out.write(sendData.toString().getBytes("UTF-8")); out.flush()` – vanOekel Apr 12 '14 at 13:50
  • I'm guessing that what Kode Charlie says is correct, but after hours of searching online I can't find any other way to do it! – boiiocks Apr 13 '14 at 08:38
  • Considering point 2 in [this answer](http://stackoverflow.com/a/8294127/3080094), I'm not sure what Kode Charlie suggests can be done. But I can't explain the difference in what Wireshark shows either. Maybe a comparison of what is received over the wire in both cases can give some insight. – vanOekel Apr 13 '14 at 22:16

0 Answers0