JAVA – How To Post To A HTML/PHP Post Form

This example shows how to build up a string to post to a web form, and return the results generated.

Element1 is the first variable the the post accepts – “Value 1” is the literal string bieng passed to it.
Element2 is the second variable that the post accepts – “Value 2” is the literal string bieng passed to it.
Element3 is the third variable that the post accepts – “Value 2” is the literal string bieng passed to it.

http://www.examplewebsite.asp is the web page that the data is bieng posted to.

 

//Create Post String
String data = URLEncoder.encode(“Element1”, “UTF-8”) + “=” + URLEncoder.encode(“Value 1”, “UTF-8”);
data += “&” + URLEncoder.encode(“Element2”, “UTF-8”) + “=” + URLEncoder.encode(“Value 2”, “UTF-8”);
data += “&” + URLEncoder.encode(“Element3”, “UTF-8”) + “=” + URLEncoder.encode(“Value 3”, “UTF-8”);
                
         
// Send Data To Page
URL url = new URL(“http://www.examplewebsite.asp”);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
   
// Get The Response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
        System.out.println(line);
        //you Can Break The String Down Here
}

 

You can manipulate the line variable to read in the information returned from the post.

Advertisements

5 thoughts on “JAVA – How To Post To A HTML/PHP Post Form

  1. This looks excellent, exactly what I’m looking for. But unfortunately it doesn’t work..

    I send it to my webpage and it doesn’t post the message. I included this piece of code in my php website: “print_r($_POST);”, which shows all the post-variables send but its empty…

    If you have any ideas about what it could be, I would appreciate it much…

  2. Got it! You need to add the “index.php” at the end of your url.

    Thank you for this wonderfull piece of code!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s