java 如何使用java代码登录网站?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35080166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:42:26  来源:igfitidea点击:

how to login into website using java code?

javaloginweb-testing

提问by Ys3

I want to write code for login to websites with java.

我想用java编写登录网站的代码。

Here is the code :

这是代码:

package login;

import java.net.*;
import java.io.*;

public class ConnectToURL {

    // Variables to hold the URL object and its connection to that URL.
    private static URL URLObj;
    private static URLConnection connect;

    public static void main(String[] args) {
        try {
            CookieManager cManager = new CookieManager();
            CookieHandler.setDefault(cManager);
            // Establish a URL and open a connection to it. Set it to output mode.
            URLObj = new URL("https://accounts.google.com/ServiceLogin?service=mail&continue=https://mail.google.com/mail/#identifier");
            connect = URLObj.openConnection();
            connect.setDoOutput(true);  
        }
        catch (MalformedURLException ex) {
            System.out.println("The URL specified was unable to be parsed or uses an invalid protocol. Please try again.");
            System.exit(1); 
        }
        catch (Exception ex) {
            System.out.println("An exception occurred. " + ex.getMessage());
            System.exit(1);
        }

        try {
            // Create a buffered writer to the URLConnection's output stream and write our forms parameters.
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream()));
            writer.write("[email protected]&Passwd=123456&submit=Login");
            writer.close();

            // Now establish a buffered reader to read the URLConnection's input stream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));

            String lineRead = "";

            // Read all available lines of data from the URL and print them to screen.
            while ((lineRead = reader.readLine()) != null) {
                System.out.println(lineRead);
            }

            reader.close();
        }
        catch (Exception ex) {
            System.out.println("There was an error reading or writing to the URL: " + ex.getMessage());
        }
    }
}

I have tried this code on Facebook and Gmail but the problem is that it didn't work.

我已经在 Facebook 和 Gmail 上尝试过这段代码,但问题是它不起作用。

It keep telling me that the cookies is not enabled. (I have used chrome browser and they were enabled).

它一直告诉我未启用 cookie。(我使用过 chrome 浏览器并且它们已启用)。

Is there any other ways to achieve this?

有没有其他方法可以实现这一目标?

采纳答案by nazar_art

If your goal is just login to some web site, much better solution is to use Selenium Web Driver.

如果您的目标只是登录某个网站,更好的解决方案是使用Selenium Web Driver

It has API for creating modern drivers instances, and operate with their web elements.

它具有用于创建现代驱动程序实例的 API,并使用其 Web 元素进行操作。

Code example:

代码示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class Example  {

    public static void main(String[] args) {
        // Create a new instance of the html unit driver
        // Notice that the remainder of the code relies on the interface, 
        // not the implementation.
        WebDriver driver = new HtmlUnitDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());

        driver.quit();
    }
}

Also it has solution how to manage cookies as well - Cookies

它还提供了如何管理 cookie 的解决方案 - Cookies

Just look at documentation how to configure driver instances and manage web elements, preferred way is to use Page Object pattern.

只需查看文档如何配置驱动程序实例和管理 Web 元素,首选方法是使用页面对象模式

Update:

更新:

For getting location from web page which doesn't have idor nameattributes can be done using xpath expressions, very useful for this can be firefox extensions like:

要从没有idname属性的网页中获取位置,可以使用 xpath 表达式完成,对此非常有用的是 firefox 扩展,例如:

And use concisely and short Xpath functions.

并使用简明扼要的Xpath 函数

For example:

例如:

<table>
    <tr>
        <td>
            <p>some text here 1</p>
        </td>
    </tr>
    <tr>
        <td>
            <p>some text here 2</p>
        </td>
    </tr>
    <tr>
        <td>
            <p>some text here 3</p>
        </td>
    </tr>
</table>

for getting text some text here 2you able to use following xpath:

要获取文本,some text here 2您可以使用以下 xpath:

//tr[2]/td/p

//tr[2]/td/p

if you know that text is static you able to use contains():

如果您知道文本是静态的,您可以使用contains()

//p[contains(text(), 'some text here 2')]

//p[contains(text(), '这里有一些文字 2')]

For checking if your xpath is unique at this page the best is to use console.
How to do is described here How to verify an XPath expression

要检查您的 xpath 在此页面上是否唯一,最好使用控制台。
这里描述了如何如何验证 XPath 表达式

回答by William Dunne

What exactly are you trying to do with this? You are almost certainly better off using something like Selenium web-driver for browser automation tasks, as you piggy back on the work of an existing web-browser to handle things like cookies.

你到底想用这个做什么?您几乎肯定最好使用 Selenium 网络驱动程序来执行浏览器自动化任务,因为您可以依靠现有网络浏览器的工作来处理 cookie 之类的事情。

In this case, you're talking about your web browser saying cookies are not enabled, but you're not actually using a web browser, you're sending a connection via your java application.

在这种情况下,您是在说您的网络浏览器说未启用 cookie,但您实际上并未使用网络浏览器,而是通过您的 Java 应用程序发送连接。