2013-04-04 159 views
1

我想登录到一个网站,但如果我尝试使用此代码: 程序包URL;登录网站(Java)

//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和登录信息?

感谢您的所有建议。

+0

我可以使用HtmlUnit,对于这样的工作,因为它不仅支持Cookie,而且JavaScript的。 – MrSmith42 2013-04-04 18:45:25

+0

您尝试访问的页面是一个简单的HTML页面 - 您应该使用https://login.szn.cz/loginProcess代替。另外,您需要使用SSL连接。此外,您需要将请求方法指定为POST,将Content-Type指定为“application/x-www-form-urlencoded”。此外,您还需要对要写入请求正文的数据进行编码。此外,您似乎缺少一些参数(至少与使用主HTML页面登录时相比)。您可能需要HtmlUnit,正如@ MrSmith42所建议的那样。 – Perception 2013-04-04 18:55:22

+0

您可以尝试将'connect'连接到'HttpURLConnection',然后使用'setRequestMethod(“POST”)将请求方法设置为POST;' – srkavin 2013-04-04 18:56:21

回答

0

您可以调用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 
    // ... 
} 

甲新URLConnection对象通过调用协议处理程序的这一URLopenConnection方法创建的每个时间。

也看到这些链接..

+1

我使用MrSmith42的建议形式,但谢谢你的回复:) – Sk1X1 2013-04-04 19:46:56