Creating HTTP POST Requests
POST (and PUT) requests send data to the server. For a POST request, you need to turn on the output mode of HttpUrlConnection
and set the content type:
connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true);
Next, to upload the data, here assumed to be a String, use code like the following:
DataOutputStream out = Â Â Â Â Â Â Â Â new DataOutputStream( connection.getOutputStream() ); out.writeBytes(content); out.flush(); out.close();
With web browsing, most POST requests send form data. From Java programs, however, you are more likely to upload JSON or XML data with POST and PUT requests. Once you upload the data, your program should read the response, especially to see whether the request was successful.
Exercise 3: Sending JSON Data with POST Requests
In this exercise, we'll send a small JSON object...