Here is the code I am using. Instead of posting data to the page, it is downloading it like a regular text file. So, I am actually getting the html code returned and the form is not being submitted.
I know the html form works. If I open it in a browser, I can post to it and my data appears in my database. I'm guessing I'm missing a parameter or something.
public void testComm ()
{
try
{
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
url = new URL ("http://mysite.com/myform.html");
// URL connection channel.
urlConn = url.openConnection();
// Let the run-time system (RTS) know that we want input.
urlConn.setDoInput (true);
// Let the RTS know that we want to do output.
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
// Specify the content type.
urlConn.setRequestProperty
("Content-Type", "application/x-www-form-urlencoded");
// Send POST output.
printout = new DataOutputStream (urlConn.getOutputStream ());
String content =
"txtLevelName=" + URLEncoder.encode ("level1") +
"&txtLevelData=" + URLEncoder.encode ("abcd");
printout.writeBytes (content);
printout.flush ();
printout.close ();
// Get response data.
input = new DataInputStream (urlConn.getInputStream ());
String str;
while (null != ((str = input.readLine())))
{
System.out.println (str);
}
input.close ();
}
catch (MalformedURLException me)
{
System.err.println("MalformedURLException: " + me);
}
catch (IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
You're already sending a POST request. It's the urlConn.setDoOutput(true) which sets the request method to POST. Apparently you're sending the request to the wrong URL. Open the HTML page in your browser. Rightclick and View Source. Locate the HTML <form> element in the HTML source. It should look something like:
<form action="http://mysite.com/somescript" method="post">
Check its action attribute. That's exactly the URL which you have to POST to.
Probably you are not doing it right. Looks like you are posting it to the form instead of the action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With