19

How to post JSON data using HttpURLConnection? I am trying 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();

StringReader reader = new StringReader("{'value': 7.5}");
OutputStream os = httpcon.getOutputStream();

char[] buffer = new char[4096];
int bytes_read;    
while((bytes_read = reader.read(buffer)) != -1) {
    os.write(buffer, 0, bytes_read);// I am getting compilation error here
}
os.close();

I am getting compilation error in line 14.

The cURL request is:

curl -H "Accept: application/json" \
-H "Content-Type: application/json" \
-d "{'value': 7.5}" \
"a URL"

Is this the way to handle cURL request? Any information will be very helpful to me.

Thanks.

Tapas Bose
  • 28,796
  • 74
  • 215
  • 331

2 Answers2

31

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();
ykaganovich
  • 14,736
  • 8
  • 59
  • 96
  • Is it not possible to send a complex json object in this manner? For instance ... "{"points":[{"point":{"latitude":40.8195085182092,"longitude":-73.75127574479318},"description":"test"},{"point":{"latitude":40.2195085182092,"longitude":-74.75127574479318},"description":"test2"}],"mode":"WALKING"}" ... is an object that I'm sending via this method and I get an HTTP Response Code of 500. – crowmagnumb Dec 03 '13 at 04:30
  • @CrowMagnumb You should post a separate question. 500 means that the server has an internal error trying to process your request. – ykaganovich Dec 03 '13 at 19:59
  • OK, I've done so [here](http://stackoverflow.com/questions/20452366/http-response-code-500-sending-complex-json-object-using-httpurlconnection) Thanks for the suggestion. – crowmagnumb Dec 08 '13 at 10:34
9

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();
Anthony Chuinard
  • 1,028
  • 10
  • 17