Java自动登录网站。不起作用

Java自动登录网站。不起作用,java,httpurlconnection,Java,Httpurlconnection,我想创建一个java应用程序,它可以自动登录到一个网站并做一些事情。我正在本地主机上测试它。实际上,我在这方面是一个全新的人,我正试图从中获得概念,并修改代码,使之真正适用于我的本地主机 package random; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.n

我想创建一个java应用程序,它可以自动登录到一个网站并做一些事情。我正在本地主机上测试它。实际上,我在这方面是一个全新的人,我正试图从中获得概念,并修改代码,使之真正适用于我的本地主机

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);
    }

}
应该是:

con.addRequestProperty("Content-Length", Integer.toString(params.length()));
有一个迷路的“:”。我现在已经修好了

但是,我的代码仍然没有实际登录,我仍然需要帮助。 我已经把我的全部计划放在这里了

我可能错了,但我认为这些参数实际上并没有写入代码中的con.getOutputStream():

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

内容长度设置为
Integer.toString(params.Length())

我的猜测是,以字节形式写入的
参数比
内容长度长,并且服务器接收的字节比预期的多

尝试:


这显然取决于您的编码。另请查看。

413请求的实体太长。标题可能设置不正确。我相信addRequestProperty没有设置头。您可能必须显式发送标题。413是“请求太大”,所以您的帖子参数太大。@Kevin我的参数太小了。电子邮件=管理员%40admin.com和密码=password@user3365097你能用网络浏览器登录吗?@RaviH我不太清楚你的意思。我对这个完全陌生。请你详细解释一下,我已经找到了导致413的原因并改正了。但它仍然没有登录。请帮忙?
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                wr.writeBytes(params);
                wr.flush();
                wr.close();
con.addRequestProperty("Content-Length:", Integer.toString(params.getBytes("UTF-8").length()));