登录网站(Java)

时间:2013-04-04 18:36:19

标签: java login

我想登录网站,但如果我尝试使用此代码: 包URL;

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

我收到此错误:

  

读取或写入URL时出错:服务器返回HTTP   响应代码:405代表网址:http://login.szn.cz

这是我如何登录这个网站的方式吗?或者我可以在Opera浏览器中使用cookie和登录信息吗?

感谢所有建议。

1 个答案:

答案 0 :(得分:0)

您可以调用URL对象的openConnection方法来获取URLConnection对象。您可以使用此URLConnection对象来设置连接前可能需要的参数和常规请求属性。只有在调用URL方法时,才会启动与URLConnection.connect表示的远程对象的连接。以下代码打开与站点 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
    // ...
}

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

另见这些链接..