Reputation: 47
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?
Upvotes: 2
Views: 5718
Reputation: 160181
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.
Upvotes: 7