5

I have an HTML form that looks about like this:

<form name="form1" method="post" action="/confirm.asp">
    <input type="text" name="data1" size="20" value=""><br>
    <input type="text" name="data2" size="20" value=""><br>
    <input type="Submit" name=submit value="Submit">
</form>

I want to use Java to pass data todata1 and data2 and read the page that follows when the form is submitted. Since this is a method=post, I cannot use http://somesite.com/confirm.asp?data1=foo&data2=foo.

Can one please help?

4 Answers4

4
/* create a new URL and open a connection */
URL url = new URL("http://somesite.com/confirm.asp");
URLConnection con = url.openConnection();
con.setDoOutput(true);

/* wrapper the output stream of the connection with PrintWiter so that we can write plain text to the stream */
PrintWriter wr = new PrintWriter(con.getOutputStream(), true);

/* set up the parameters into a string and send it via the output stream */
StringBuilder parameters = new StringBuilder();
parameters.append("data1=" + URLEncoder.encode("value1", "UTF-8"));
parameters.append("&");
parameters.append("data2=" + URLEncoder.encode("value2", "UTF-8"));
wr.println(parameters);
wr.close();

/* wrapper the input stream of the connection with BufferedReader to read plain text, and print the response to the console */
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = br.readLine()) != null) System.out.println(line);
br.close();
Eng.Fouad
  • 107,075
  • 62
  • 298
  • 390
  • I'm a Java novice. Can you explain the code? What do I have to change? `value1` and `value2` to the data I want to pass? And then is `line` the html source of the page after the form is submitted? – Christina Stewart Jul 16 '12 at 02:37
  • Wouldn't parameters be "data1=value1data2=value2"? – Jon Lin Jul 16 '12 at 02:37
  • I used `URLEncoder` in case of using spaces or special characters like `+`. – Eng.Fouad Jul 16 '12 at 02:39
  • No, I mean there's nothing separating the 2 pairs, (no "&") – Jon Lin Jul 16 '12 at 02:42
  • Eng.Fouad, sir, can you please respond to my questions? I think this is kind of what I'm looking for! – Christina Stewart Jul 16 '12 at 02:42
  • Wow, thank you so much. One more thing, how do I accept cookies from the site? When I run the program, the response is a page with the html source saying that my cookies are disabled and that I need to allow cookies to view submit the form. Can you help? – Christina Stewart Jul 16 '12 at 02:49
  • @ChristinaStewart I don't know how to enable the cookies, but you may take a look on 3rd-party libraries such as: [`Apache Commons HttpClient`](http://hc.apache.org/httpclient-3.x/) and [`HtmlUnit`](http://htmlunit.sourceforge.net/). – Eng.Fouad Jul 16 '12 at 02:57
  • @ChristinaStewart Also take a look on this question: http://stackoverflow.com/questions/10673684/send-http-request-manually-via-socket – Eng.Fouad Jul 16 '12 at 03:00
  • @ChristinaStewart you can see how to maintain the session using cookies in the link provided by JonLin, in the section **Maintaining the session**. – Luiggi Mendoza Jul 16 '12 at 03:05
3

Here is the code from Link. Hope this helps you :)

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpPostForm
{
  public static void main(String[] args)
  {
    try
    {
      URL url = new URL( "http://www.aaaa.com/xyz.asp" );

      HttpURLConnection hConnection = (HttpURLConnection)
                             url.openConnection();
      HttpURLConnection.setFollowRedirects( true );

      hConnection.setDoOutput( true );
      hConnection.setRequestMethod("POST"); 

      PrintStream ps = new PrintStream( hConnection.getOutputStream() );
      ps.print("param1=abcd&amp;param2=10341");
      ps.close();

      hConnection.connect();

      if( HttpURLConnection.HTTP_OK == hConnection.getResponseCode() )
      {
        InputStream is = hConnection.getInputStream();
        OutputStream os = new FileOutputStream("output.html");
        int data;
        while((data=is.read()) != -1)
        {
          os.write(data);
        }
        is.close();
        os.close();
        hConnection.disconnect();
      }
    }
    catch(Exception ex)
    {
      ex.printStackTrace();
    }
  }
}
hqt
  • 27,058
  • 46
  • 161
  • 235
2

To write a POST request in Java, you should connect to your target URL via a URLConnection, where you then write the bytes of head boundary, the boundary message (where the keys, values, and any other request data is placed), and the end boundary.

I wrote a PostProcess class for an application of mine, which allows for asynchronous POST request uploading, key-value parameters, file parameters (i.e. the file upload input in a form), and upload progress tracking. It also records the server response.

For the sake of size and readability, I have uploaded the code externally to http://textu.be/T

FThompson
  • 27,043
  • 11
  • 53
  • 89
1

Try following codes

String url="www.somesite.com";     
Document doc = Jsoup.connect(url).data("data1", "foo").data("data2","foo")
                .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                .referrer("http://www.google.com").post();
theMind
  • 176
  • 1
  • 10