2011-03-02 36 views
0

任何人都可以幫我弄清楚爲什麼這段代碼不工作?它應該登錄到HTS,但它不起作用。它沒有給我任何錯誤信息或任何東西,只是沒有結果。任何幫助,將不勝感激。登錄無法使用的代碼

下面的代碼:

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

public class Login { 

private static URL URLObj; 
private static URLConnection connect; 

public static void main(String[] args) { 
    try { 
     URLObj = new URL("http://www.hackthissite.org/user/login"); 
     connect = URLObj.openConnection(); 
     connect.addRequestProperty("REFERER", "http://www.hackthissite.org"); 
     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 { 
     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream())); 
     writer.write("username=BrandonHeat&password=**********&btn_submit=Login"); 
     writer.close(); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream())); 

     String lineRead = ""; 

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

} 

}

回答

0

我只是猜測,但URLConnection的文檔表明您必須已經設置的參數後連接:

1。連接對象是通過調用 上的openConnection方法創建的。
2.設置參數和一般請求屬性被操縱。
3.使用連接 方法建立到遠程對象的實際連接。
4.遠程對象變爲可用。可以訪問遠程對象的標題字段和內容 。
...
以下方法用於 訪問頭字段和連接後的 內容由 到遠程對象:

  • 的getContent
  • 的getHeaderField
  • 的getInputStream
  • getOutputStream

編輯:
你不能在URL中打開你的URL參數嗎(即http://www.hackthissite.org/user/login?username=BrandonHeat&password=xxxxx&btn_submit=Login),還是設置爲標題?

另外,在connect()之後,如果您執行getContent(),會得到什麼結果?

編輯:有一個描述的過程here

問候
紀堯姆

+0

試過這種方式爲好,還是沒有結果:( – BrandonHeat

+0

如果我(在瀏覽器中正常甚至)打開URL與參數,我得到一個消息「請使用登錄表單「getContent()爲空; – BrandonHeat

+0

好的,經過一些篡改後,我終於使它連接,現在我得到的頁面,但我不知道我是否只連接到頁面或登錄以及。我在代碼中添加了一個新部分,它在登錄後移動到另一個網站頁面,但我得到了「您需要登錄」的錯誤,但我不確定這是否是因爲我沒有首先正確登錄,或因爲我沒有通過所有必要的數據。我使用會話ID(PHPSESSID)傳遞一個cookie,還有什麼我需要添加的(或者是否有任何方法來檢查我是否真的登錄了第一頁)? – BrandonHeat