How to POST Data into website using Jsoup

Aspirant picture Aspirant · Apr 4, 2012 · Viewed 43.2k times · Source

I am trying to POST data into website to make a login into the site using Jsoup , but its not working ?

I am trying the code

    Document docs = Jsoup.connect("http://some.com/login")
        .data("cmd", "login","username", "xxxx","password", "yyyyy")
        .referrer("http://some.com/login/").post();

here it is giving normal page of login in pagesource

i have also tried the code

 Document docs = (Document) Jsoup.connect("http://some.com/login")
    .data("cmd", "login","username", "xxxx","password", "yyyyy")
    .referrer("http://some.com/login/").method(Method.POST).execute().parse();

here also it is giving normal page of login again in pagesource.

Any suggestions regarding the same would be highly appreciated !!

Thanks....

Answer

vikiiii picture vikiiii · Apr 4, 2012

I will give the answer of your question by taking an example. Suppose you want to login to facebook.

Then apart from username and password there are many other parameters that are also passed through POST request. Those all parameters are hidden and are passed similarly like username and password. For Example :

If you will open the html source of facebook , then you can see there is one parameter which is hidden is lgnrnd and its value is 071129_5D7M.

So there are many other parameter similar like this.You need to pass all the parameters. You should also specify the userAgent.

Document doc = Jsoup.connect("http://www.facebook.com")
.data("email", "myemailid")
.data("pass", "mypassword")
// and other hidden fields which are being passed in post request.
.userAgent("Mozilla")
.post();
System.out.println(doc); // will print html source of homepage of facebook.