views:

547

answers:

5

I wan't to login to a website through Java and perform operations, like click, add text to a textfield, etc., through Java.

+6  A: 

I suggest using a testing framework like HtmlUnit. Even through it's designed for testing, it's a perfectly good programmatic "navigator" of remote websites.

Here's some sample code from the site, showing how to navigate to a page and fill in a form:

public void submittingForm() throws Exception {
   WebClient webClient = new WebClient();
   HtmlPage page1 = webClient.getPage("http://some_url");
   HtmlForm form = page1.getFormByName("myform");
   HtmlSubmitInput button = form.getInputByName("submitbutton");
   HtmlTextInput textField = form.getInputByName("userid");
   textField.setValueAttribute("root");
   HtmlPage page2 = button.click();
}
skaffman
Thanks for the code.There is one errorNoClassDefinationFoundError: org/apache/commons/httpclient/auth/CredentialsProviderFrom where can I download that library.Can you provide me the link
Yatendra Goel
http://htmlunit.sourceforge.net/dependencies.html
skaffman
Thanks a lot.I have setup all the things. But there is one runtime exception. Can we chat for 10 min. I need your help in removing cookies related exception.
Yatendra Goel
@Yatendra Goel: Post another question to solve your problems with that "runtime exception"
OscarRyz
+3  A: 

You could launch it by

Runtime.getRuntime().exec("command-line command to launch IE");

then use Java's Robot class to send mouse clicks and fill in text. This seems rather crude, though, and you can probably do better by communicating directly with the web server (bypassing the browser entirely).

Bill the Lizard
A: 

If you really need a 'real' IE you could try Watij, if you just need browser features in java I recommend HttpClient

Update: as the OP indicated using a real browser was not needed/wanted. An example of a form login using HttpClient can be found here: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/httpclient/src/examples/org/apache/http/examples/client/ClientFormLogin.java

Simon Groenewolt
I don't want real IE. I just want to login to a page and then have the page source of the page that comes after login.Can you help in giving the code that can perform this login. I want to login to orkut.com through java
Yatendra Goel
Updated my answer. (And, if you don't want IE you should not mention it in the title of your question ;-)
Simon Groenewolt
+1  A: 

This question's answers may be helpful.

But you should consider direct HTTP as a better way to interact with websites.

Vanya
A: 

You could also use WebTest from Canoo which actually uses HTMLUnit but with an extra layer on top of it. Should be easier to start du to the scripting layer and it comes with additional abstractions for sending mails, verifying output etc.

http://webtest.canoo.com/webtest/manual/WebTestHome.html

MrWhite