Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you execute an http post in Java?

Tags:

java

http

post

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());
    }
}   
like image 416
Mike Brascome Avatar asked Apr 30 '26 08:04

Mike Brascome


2 Answers

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.

See also:

  • Using java.net.URLConnection to fire and handle HTTP requests
like image 151
BalusC Avatar answered May 02 '26 22:05

BalusC


Probably you are not doing it right. Looks like you are posting it to the form instead of the action.

like image 22
Sid Malani Avatar answered May 02 '26 23:05

Sid Malani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!