Visualizzazione dei risultati da 1 a 3 su 3
  1. #1
    Utente di HTML.it
    Registrato dal
    Jul 2017
    Messaggi
    2

    Programma java per il login automatico a sito web

    Buongiorno, vorrei sviluppare un programma per l'accesso veloce al sito della mia banca.
    Ho trovato su internet un esempio per collegarsi al sito web gmail con l'account di google.
    Purtroppo l'esecuzione dell'esempio mi dà errore.
    Premetto che ho eseguito il programma all'interno di Netbeans.
    Il programma è questo:

    codice:
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package loginautomatico;
    
    /**
     *
     * @author sanp
     */
    
    
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.net.CookieHandler;
    import java.net.CookieManager;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.ArrayList;
    import java.util.List;
    import javax.net.ssl.HttpsURLConnection;
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.nodes.Element;
    import org.jsoup.select.Elements;
    
    public class LoginAutomatico{
    
      private List<String> cookies;
      private HttpsURLConnection conn;
    
      private final String USER_AGENT = "Mozilla/5.0";
    
      public static void main(String[] args) throws Exception {
    
        String url = "https://accounts.google.com/ServiceLoginAuth";
        String gmail = "https://mail.google.com/mail/";
    
        LoginAutomatico http = new LoginAutomatico();
    
        // make sure cookies is turn on
        CookieHandler.setDefault(new CookieManager());
    
        // 1. Send a "GET" request, so that you can extract the form's data.
        String page = http.GetPageContent(url);
        String postParams = http.getFormParams(page, "m51@gmail.com", "rum");
    
        // 2. Construct above post's content and then send a POST request for
        // authentication
        http.sendPost(url, postParams);                 // <==================== riga 54
    
        // 3. success then go to gmail.
        String result = http.GetPageContent(gmail);
        System.out.println(result);
      }
    
      private void sendPost(String url, String postParams) throws Exception {
    
        URL obj = new URL(url);
        conn = (HttpsURLConnection) obj.openConnection();
    
        // Acts like a browser
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Host", "accounts.google.com");
        conn.setRequestProperty("User-Agent", USER_AGENT);
        conn.setRequestProperty("Accept",
            "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        for (String cookie : this.cookies) {                                               // <=================== riga 74
            conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
        }
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Referer", "https://accounts.google.com/ServiceLoginAuth");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
    
        conn.setDoOutput(true);
        conn.setDoInput(true);
    
        // Send post request
        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 : " + 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();
        // System.out.println(response.toString());
    
      }
    
      private String GetPageContent(String url) throws Exception {
    
        URL obj = new URL(url);
        conn = (HttpsURLConnection) obj.openConnection();
    
        // default is GET
        conn.setRequestMethod("GET");
    
        conn.setUseCaches(false);
    
        // act like a browser
        conn.setRequestProperty("User-Agent", USER_AGENT);
        conn.setRequestProperty("Accept",
            "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
            System.out.println("cookies..0 ");
        if (cookies != null) {
            System.out.println("cookies..1 ");
    
                for (String cookie : this.cookies) {
                conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
            }
        }
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + 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();
    
        // Get the response cookies
        setCookies(conn.getHeaderFields().get("Set-Cookie"));
    
        return response.toString();
    
      }
    
      public String getFormParams(String html, String username, String password)
            throws UnsupportedEncodingException {
    
        System.out.println("Extracting form's data...");
    
        Document doc = Jsoup.parse(html);
    
        // Google form id
        Element loginform = doc.getElementById("gaia_loginform");
        Elements inputElements = loginform.getElementsByTag("input");
        List<String> paramList = new ArrayList<String>();
        for (Element inputElement : inputElements) {
            String key = inputElement.attr("name");
            String value = inputElement.attr("value");
    
            if (key.equals("Email"))
                value = username;
            else if (key.equals("Passwd"))
                value = password;
            paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
        }
    
        // build parameters list
        StringBuilder result = new StringBuilder();
        for (String param : paramList) {
            if (result.length() == 0) {
                result.append(param);
            } else {
                result.append("&" + param);
            }
        }
        return result.toString();
      }
    
      public List<String> getCookies() {
        return cookies;
      }
    
      public void setCookies(List<String> cookies) {
        this.cookies = cookies;
      }
    
    }
    L'output dell'esecuzione:

    codice:
    run:
    cookies..0 
    
    Sending 'GET' request to URL : https://accounts.google.com/ServiceLoginAuth
    Response Code : 200
    Extracting form's data...
    Exception in thread "main" java.lang.NullPointerException
        at loginautomatico.LoginAutomatico.sendPost(LoginAutomatico.java:74)
        at loginautomatico.LoginAutomatico.main(LoginAutomatico.java:54)
    Java Result: 1

  2. #2
    Utente di HTML.it
    Registrato dal
    Jul 2017
    Messaggi
    2
    Adesso sono riuscito a non farlo andare in errore di NullPointer .....!?
    l'output è stato:




    codice:
    Sending 'GET' request to URL : https://accounts.google.com/ServiceLoginAuth
    Response Code : 200
    Extracting form's data...
    
    Sending 'POST' request to URL : https://accounts.google.com/ServiceLoginAuth
    Post parameters : Page=PasswordSeparationSignIn&=&gxf=AFoagUVp032Kg27dAR7RNlMRFyr5464vVw%3A1501413050265&ProfileInformation=&SessionState=&_utf8=%E2%98%83&bgresponse=js_disabled&Email=mariateresa.dangeli51%40gmail.com&=&signIn=Next
    Response Code : 200
    cookies..0 
    cookies..1 
    
    Sending 'GET' request to URL : https://mail.google.com/mail/
    Response Code : 200
    <!DOCTYPE html><html lang="en">  <head>  <meta charset="utf-8">  <meta content="width=300, initial-scale=1" name="viewport">  <meta name="description" content="Gmail is email that&#39;s intuitive, efficient, and useful. 15 GB of storage, less spam, and mobile access.">  <meta name="google-site-verification" content="LrdTUW9psUAMbh4Ia074-BPEVmcpBxF6Gwf0MSgQXZs">  <title>Gmail</title>  <style>  @font-face {  font-family: 'Open Sans';  font-style: normal;  font-weight: 300;  src: local('Open Sans Light'), local('OpenSans-Light'), url(//fonts.gstatic.com/s/opensans/v14/DXI1ORHCpsQm3Vp6mXoaTYnF5uFdDttMLvmWuJdhhgs.ttf) format('truetype');}@font-face {  font-family: 'Open Sans';  font-style: normal;  font-weight: 400;  src: local('Open Sans'), local('OpenSans'), url(//fonts.gstatic.com/s/opensans/v14/cJZKeOuBrn4kERx......
    
    ...... ecc.
    Non vedo pero' la pagina HTML .. da dove devo lanciare il programma java ? Scusate l'inesperienza ....

  3. #3
    Utente di HTML.it
    Registrato dal
    Jul 2017
    Messaggi
    2
    Scusate, ho seguito questo tutorial ma non riesco a capire come eseguirlo. Mi aspetto di vedere la pagina del sito gmail.!?
    https://www.mkyong.com/java/how-to-a...-java-example/
    Qualcuno puo' aiutarmi? Grazie.

Tag per questa discussione

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.