Black Magic
Black Magic

Reputation: 2766

Logging in on website programmatically

I have used this tutorial to try to login to a website from the company I am doing my internship at: http://www.mkyong.com/java/how-to-automate-login-a-website-java-example/

However, It is not logging in, since the URL when you're logged in to the site is the same as when you're not logged in. So all that happens is me adding the data to the fields, and then the page refreshes, with nothing happening. Can anyone tell me how I am supposed to continue?

Thanks

(Edit): I only have a redirect link

public class ProfileLogin extends AsyncTask<Void, Void, Void>{

    private List<String> cookies;
    private HttpsURLConnection conn;

    private final String USER_AGENT = "Mozilla/5.0";
    private String page;
    private String userName;
    private String passWord;
    private String postParams;
    URL obj;

    //Setting up  out connection
    public ProfileLogin(String user, String pass){
        CookieManager cManager = new CookieManager();
        CookieHandler.setDefault(cManager);
        page = null;
        try {
            obj = new URL(LOGIN_URL);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //Setting the username and password
        userName = user;
        passWord = pass;

        try {
            conn = (HttpsURLConnection) obj.openConnection();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //Starting our Asynctask to do all of the networking
        execute();
    }

    public VpnProfile getProfiles(){
        VpnProfile profile = new VpnProfile(null);
        return profile;
    }

    public String getPageContent() throws Exception{
        //Set Get method
        conn.setRequestMethod("GET");

        conn.setUseCaches(false);

        //The properties of our site, we need to act like a browser
        conn.setRequestProperty("User-Agent", USER_AGENT);
        conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        conn.setRequestProperty("Accept-Language", "nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4");

        if(cookies != null){
            for(String cookie : this.cookies){
                conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
            }
        }
        int responseCode = conn.getResponseCode();

        System.out.println("\nSending 'GET' request to URL : " + LOGIN_URL);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while((inputLine = in.readLine()) != null){
            response.append(inputLine);
        }
        in.close();
        setCookies(conn.getHeaderFields().get("Set-Cookie"));
        return response.toString();
    }   

    private String getFormParams(String userName2, String passWord2) throws Exception{
        System.out.println("Extract form's data...");

        Document doc = Jsoup.parse(page);

        //Elements of the login page
        Element userNameElement = doc.getElementById("username");
        Element passWElement = doc.getElementById("password");

        List<String> paramList = new ArrayList<String>();
        paramList.add(userNameElement.attr("name") + "=" + URLEncoder.encode(userName2, "UTF-8"));
        paramList.add(passWElement.attr("name") + "=" + URLEncoder.encode(passWord2, "UTF-8"));

        StringBuilder result = new StringBuilder();
        for(String param : paramList){
            if(result.length() == 0){
                result.append(param);
            } else {
                result.append("&" + param);
            }
        }
        return result.toString();
    }   

    private void sendPost(String postParams) throws Exception {
        conn = (HttpsURLConnection) obj.openConnection();

        //Act like a browser
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        //This line is deleted, I can't show the url, I set the host here
        conn.setRequestProperty("User-Agent", USER_AGENT);
        conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        conn.setRequestProperty("Accept-Language", "nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4");
        if(cookies != null){
            for(String cookie : this.cookies){
                System.out.println("This is cookies: " + cookie);
                conn.addRequestProperty("cookie", cookie.split(";", 1)[0]);
            }
        }
        conn.setRequestProperty("Connection", "keep-alive");
        //Deleted line setting referer URL
        conn.setRequestProperty("Content-Type", "text/html; charset=UTF-8");
        conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));

        conn.setDoOutput(true);
        conn.setDoInput(true);

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + LOGIN_URL);
        System.out.println("Post parameters : " + postParams);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while((inputLine = in.readLine()) != null){
            response.append(inputLine);
        }
        in.close();

    } 

    @Override
    protected Void doInBackground(Void... arg0) {
        try {
            page = getPageContent();
            postParams = getFormParams(userName, passWord);
            sendPost(postParams);
            page = getPageContent();
            Document doc = Jsoup.parse(page);
            Element userNameElement = doc.getElementById("username");
            if(userNameElement.toString() != null){
                System.out.println("Not logged in");
            }else{
                System.out.println("Logged in!");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }


    private void setCookies(List<String> cookies) {
        this.cookies = cookies;
    }

}

Upvotes: 3

Views: 27628

Answers (1)

Black Magic
Black Magic

Reputation: 2766

I kind of found a way around: How to log into Facebook programmatically using Java?

This works really well for me and gives me really clean and short code :)

Upvotes: 4

Related Questions