2013-04-04 156 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