How to post JSON data using HttpURLConnection? I am trying this:
HttpURLConnection httpcon = (HttpURLConnection) ((new URL(\"a url\").openConnection()));
htt
OutputStream expects to work with bytes, and you're passing it characters. Try this:
HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
byte[] outputBytes = "{'value': 7.5}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
os.close();
You may want to use the OutputStreamWriter class.
final String toWriteOut = "{'value': 7.5}";
final OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write(toWriteOut);
osw.close();