lets assume this URL...
http://www.example.com/page.php?id=10
(Here id needs to be sent in a POST request)
I want to send the id = 10
to the server's page.php
, which accepts it in a POST method.
How can i do this from within Java?
I tried this :
URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();
But I still can't figure out how to send it via POST
simplest way to send parameters with the post request:
You have done. now you can use
responsePOST
. Get response content as string:I recomend use http-request built on apache http api.
Call
HttpURLConnection.setRequestMethod("POST")
andHttpURLConnection.setDoOutput(true);
Actually only the latter is needed as POST then becomes the default method.A simple way using Apache HTTP Components is
Take a look at the Fluent API
Sending a POST request is easy in vanilla Java. Starting with a
URL
, we need t convert it to aURLConnection
usingurl.openConnection();
. After that, we need to cast it to aHttpURLConnection
, so we can access itssetRequestMethod()
method to set our method. We finally say that we are going to send data over the connection.We then need to state what we are going to send:
Sending a simple form
A normal POST coming from a http form has a well defined format. We need to convert our input to this format:
We can then attach our form contents to the http request with proper headers and send it.
Sending JSON
We can also send json using java, this is also easy:
Remember that different servers accept different content-types for json, see this question.
Sending files with java post
Sending files can be considered more challenging to handle as the format is more complex. We are also going to add support for sending the files as a string, since we don't want to buffer the file fully into the memory.
For this, we define some helper methods:
We can then use these methods to create a multipart post request as follows:
The first answer was great, but I had to add try/catch to avoid Java compiler errors.
Also, I had troubles to figure how to read the
HttpResponse
with Java libraries.Here is the more complete code :