Sending HTTP POST Request In Java

Jazz picture Jazz · Jul 24, 2010 · Viewed 764.8k times · Source

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

Answer

mhshams picture mhshams · Jul 24, 2010

Updated Answer:

Since some of the classes, in the original answer, are deprecated in the newer version of Apache HTTP Components, I'm posting this update.

By the way, you can access the full documentation for more examples here.

HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/");

// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

if (entity != null) {
    try (InputStream instream = entity.getContent()) {
        // do something useful
    }
}

Original Answer:

I recommend to use Apache HttpClient. its faster and easier to implement.

HttpPost post = new HttpPost("http://jakarata.apache.org/");
NameValuePair[] data = {
    new NameValuePair("user", "joe"),
    new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.

for more information check this url: http://hc.apache.org/