Search code examples
javarequestxmlhttprequestunirest

Java: Post-request to login on remote website, which using javascript on login-button


I'm using Unirest with Java, trying to login on a remote webpage.

I can see with Chrome developer tools and HTTP Trace that the site is using POST with XMLHttpRequest in header:

POST [site]/Services/UserService.asmx/Authenticate
Origin: [site]
X-DevTools-Emulate-Network-Conditions-Client-Id: 86825bab-dcb4-4bef-885e-5350c11fe43b
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Content-Type: application/json; charset=UTF-8
Accept: /
Referer: [site]
Accept-Encoding: gzip, deflate, br
Accept-Language: da-DK,da;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: ASP.NET_SessionId=xgea1elpr3dmrgbsotcghu5k; _ga=GA1.2.632065975.1472

If I inspect the source code of the site, I can see they are using javascript .onClick() on the submit button. Here are the code-snip of the javascript part which processing username and password (it's in the .onClick()):

    ...
    var service = new Website.Services.UserService();
                    service.Authenticate(email, password, rememberMe, referrer, 

function(result) {

                    if (!result.Authenticated) {
                        var message = result.Message || "Det var ikke muligt at logge ind med din e-mail og kode";

                        button.closest("fieldset").find(".error-text").text(message).show();
                        return;
                    } else {
                        // Redirect to my page
                        location.href = result.Url;
                    }

                }, function() {

                    alert("Det var ikke muligt at få forbindelse til serveren, opdater siden og prøv igen");

                }, true);
...

My question is, can I "simulate" the above Javascript, with Unirest (or similar in Java) so I can login on the page? And if so, how?
Or is there a way to "by-pass" is?

I am familar with Selenium and PhantomJS which may could solve it, but these methods is out of the question to use, in this case.


Solution

  • I found the solution - and of course it was a very simple and pragmatic solution.

    I had to set a tick on "Preserve log" in the Chrome developer tools, do to a redirect call which overwrote the actual post data. After this, I could see the post data and could replicate it with Unirest