簡體   English   中英

Java自動登錄網站。 不起作用

[英]Java automatic-login to website. Does not work

我想創建一個Java應用程序,該應用程序自動登錄到網站並執行操作。 我正在我的本地主機上對其進行測試。 我實際上是一個全新的人,我正在嘗試從http://www.mkyong.com/java/how-to-automate-login-a-website-java-example/中獲取概念並修改代碼真正為我的本地主機工作。

package random;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class InternetAutomationPost {

    List<String> cookies;

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

    public List<String> getCookies() {
        return cookies;
    }

    private String requestWebPage(String address) {
        try {
            URL url = new URL(address);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();

            // Don't use cache. Get a fresh copy.
            con.setUseCaches(false);

            // Use post or get.
            // And default is get.
            con.setRequestMethod("GET");

            // Mimic a web browser.
            con.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            con.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
            con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            con.addRequestProperty("Connection", "keep-alive");
            con.addRequestProperty("User-Agent", "Mozilla/5.0");
            if(cookies != null) {
                con.addRequestProperty("Cache-Control", "max-age=0");
                for (String cookie : this.cookies) {
                    System.out.print(cookie.split(";", 1)[0]);
                    con.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
                }
            }

            int responseCode = con.getResponseCode();

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

            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String inputLine;
            StringBuilder response = new StringBuilder();
            while( (inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();

            // Get the response cookies
            setCookies(con.getHeaderFields().get("Set-Cookie"));

            return response.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";

    }


    private String parsePage(String page) {

        Document doc;

        try {
            doc = Jsoup.parse(page);

            Elements form = doc.getElementsByAttributeValue("action", "login.php");


            List<String> paramList = new ArrayList<String>();
            for(Element loginForm : form) {
                System.out.println(loginForm.html());
                Elements Input = loginForm.getElementsByTag("input");
                for(Element input : Input) {
                    String name = input.attr("name");
                    String value = input.attr("value");

                    if(name.equals("email")) {
                        value = "admin@admin.com";
                    } else if(name.equals("password")) {
                        value = "password";
                    } else if(name.equals("")) {
                        continue;
                    }

                    paramList.add(name + "=" + URLEncoder.encode(value, "UTF-8"));
                }
            }

            StringBuilder params = new StringBuilder();
            for(String values : paramList) {
                if(params.length() == 0) {
                    params.append(values);
                } else {
                    params.append("&" + values);
                }
            }

            System.out.println("Params: " + params);

            return params.toString();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    private void sendPostLogin(String location, String params) {
        try {
            URL url = new URL(location);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            // Don't use cache. Get a fresh copy.
            con.setUseCaches(false);

            // Use post or get. We use post this time.
            con.setRequestMethod("POST");

            // Mimic a web browser.
            con.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            con.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
            con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            con.addRequestProperty("Connection", "keep-alive");
            con.addRequestProperty("User-Agent", "Mozilla/5.0");
            if(cookies != null) {
                con.addRequestProperty("Cache-Control", "max-age=0");
                for (String cookie : this.cookies) {
                    con.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
                }
            }
            con.addRequestProperty("Content-Length", Integer.toString(params.length()));
            con.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.addRequestProperty("Host", "localhost");
            con.addRequestProperty("Origin", "http://localhost");
            con.addRequestProperty("Referrer", "http://localhost/social/index.php");

            con.setDoOutput(true);
            con.setDoInput(true);

            // Write the parameters. Send post request.
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(params);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();

            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + params);
            System.out.println("Response Code : " + responseCode);


            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String inputLine;
            StringBuilder response = new StringBuilder();
            while( (inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();

            // Get the response cookies
            setCookies(con.getHeaderFields().get("Set-Cookie"));

            System.out.println(response.toString());    


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        InternetAutomationPost object = new InternetAutomationPost();

        String page = object.requestWebPage("http://localhost/social");
        String params = object.parsePage(page);

        object.sendPostLogin("http://localhost/social/index.php", params);
    }

}

編輯:發現為什么它發送HTTP響應代碼:413。

con.addRequestProperty("Content-Length:", Integer.toString(params.length()));

本來應該:

con.addRequestProperty("Content-Length", Integer.toString(params.length()));

有一個流浪的“:”。 我已經修復了。

但是,我的代碼仍然沒有真正登錄,我仍然需要幫助。 我現在把完整的程序放在這里。

我可能是錯的,但我認為這些參數實際上並未寫入此處代碼中的con.getOutputStream()中:

DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                wr.writeBytes(params);
                wr.flush();
                wr.close();

您將Content-Length設置為Integer.toString(params.length())

我的猜測是,以字節為單位編寫的paramsContent-Length更長,並且服務器收到的字節數超出預期。

嘗試:

con.addRequestProperty("Content-Length:", Integer.toString(params.getBytes("UTF-8").length()));

這顯然取決於您的編碼。 也看看這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM