Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Java to fill out forms, possibly controlling a browser?

Tags:

java

post

cookies

Is it possibly, at this point in time, to fill out a post form through Java? The problem with me not just using other tools is that the page has to be logged in with an account, then I can fill out the form. It's a simple form, with only 3 inputs - Name, EMail, Date of birth (text). But I need the cookies set to be able to fill them out.

Here's my current method:

public static void doSubmit(String url, HashMap<String, String> data) throws Exception {
    URL siteUrl = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
    conn.setRequestProperty("Cookie", "user=john; pass=password");
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    System.out.println("Debug 1: URL = "+url);

    DataOutputStream out = new DataOutputStream(conn.getOutputStream());

    Set keys = data.keySet();
    Iterator keyIter = keys.iterator();
    String content = "";
    for(int i=0; keyIter.hasNext(); i++) {
        Object key = keyIter.next();
        if(i!=0) {
            content += "&";
        }
        content += key + "=" + URLEncoder.encode(data.get(key), "UTF-8");
    }
//  System.out.println(content);
    out.writeBytes(content);
    out.flush();
    out.close();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = "";
    while((line=in.readLine())!=null) {
        System.out.println(line);
    }
    in.close();
}

I found this method from another site, and here's the hashmap

        data.put("name", "name");
        data.put("email", "[email protected]");
        data.put("dob", "1/1/1900");
        doSubmit("link.com/index.php", data);

Is there a simpler method? Possibly controlling a browser, such as Chrome to fill it out automatically?

like image 944
user1032232 Avatar asked Jun 16 '26 14:06

user1032232


1 Answers

There's HtmlUnit and Selenium. These can be fronted by JWebUnit if you need to swap implementations.

For something as trivial as this, HttpClient might be enough, but there'd be more manual work.

like image 192
Dave Newton Avatar answered Jun 18 '26 05:06

Dave Newton



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!