java - 登录网站 (Java)

标签 java authentication

我想登录一个网站,但如果我尝试使用以下代码: 包网址;

//Variables to hold the URL object and its connection to that URL.
import java.net.*;
import java.io.*;

public class URLLogin {
    private static URL URLObj;
private static URLConnection connect;

public static void main(String[] args) {
    try {
        // Establish a URL and open a connection to it. Set it to output mode.
        URLObj = new URL("http://login.szn.cz");
        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(),"UTF-8"));
        writer.write("username=S&password=s&login=Přihlásit se");
        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());
    }
}
}

我收到此错误:

There was an error reading or writing to the URL: Server returned HTTP response code: 405 for URL: http://login.szn.cz

有什么方法可以登录该网站吗?或者我可以在 Opera 浏览器中使用 cookie 来获取登录信息?

感谢所有建议。

最佳答案

您可以调用URL对象的openConnection方法来获取URLConnection对象。您可以使用此 URLConnection 对象来设置连接之前可能需要的参数和常规请求属性。仅当调用 URLConnection.connect 方法时,才会启动与 URL 表示的远程对象的连接。以下代码打开与网站 example.com 的连接:

try {
    URL myURL = new URL("http://login.szn.cz");
    URLConnection myURLConnection = myURL.openConnection();
    myURLConnection.connect();
} 
catch (MalformedURLException e) { 
    // new URL() failed
    // ...
} 
catch (IOException e) {   
    // openConnection() failed
    // ...
}

每次调用此 URL 协议(protocol)处理程序的 openConnection 方法都会创建一个新的 URLConnection 对象。

另请参阅这些链接..

关于java - 登录网站 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15819030/

相关文章:

java - 从数组创建适配器(AutoCompleteTextView)

facebook - 自最近引入登录审核以来,我该如何测试 Facebook 应用程序?

c# - 未经授权时重定向

ios - 从 iOS 应用程序到 Safari 将身份验证 token 发送到 Safari

Java 如何求两个不同数组中元素之和?

java - 如何使用 java 以编程方式创建 odt 文件?

java - 如何在组合框 Action 监听器中仅包含用户操作?

authentication - 在 artifactory 中匿名拉取 docker repo

javascript - 如何使用ajax和php登录用户?

java - 如何在Java freechart中添加多行?