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.
Loading...
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…
Peter - July 22, 2009 at 7:44 pm
Got it! You need to add the “index.php” at the end of your url.
Thank you for this wonderfull piece of code!
Peter - July 22, 2009 at 8:10 pm