Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (19k points)

Consider the following 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

1 Answer

0 votes
by (33.1k points)

Since some of the classes, in the original answer, are deprecated in the newer version of Apache HTTP Components.

For example:

HttpClient httpclient = HttpClients.createDefault();

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

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"));

HttpResponse response = httpclient.execute(httppost);

HttpEntity entity = response.getEntity();

if (entity != null) {

    try (InputStream instream = entity.getContent()) {

    }

}

Hope this answer helps you!

Related questions

0 votes
1 answer
asked Jul 24, 2019 in Java by Nigam (4k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 9, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...