2013-01-01 34 views
1

我創建的應用程序在GAE上運行並連接到特定頁面,自動登錄到此頁面並在登錄後我想接收html並處理它。在建立java.net連接時在GAE上獲取IOException

這裏是有問題的(writer.write部分和connection.connect())的部分代碼:

 this.username = URLEncoder.encode(username, "UTF-8"); 
     this.password = URLEncoder.encode(password, "UTF-8"); 
     this.login = "login"; 

     connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoOutput(true); 
     connection.setRequestMethod("POST"); 

     OutputStreamWriter writer = new OutputStreamWriter(
       connection.getOutputStream()); 
     writer.write("str_login=" + login + "&str_user=" + username 
       + "&str_pass=" + password); 
     writer.close(); 

     connection.connect(); 

我收到IOException異常(connection.connect()),而establishig連接。問題是「application/x-www-form-urlencoded」數據。當我將錯誤的參數傳遞給頁面(例如str_pasSSs,str_usernaAAme或根本沒有參數)時,我無法登錄,但我確實得到了登錄頁面的html響應。所以,Google App Engine似乎不支持這種通信。是否有可能以GAE支持的其他方式登錄到此頁面?

在Wireshark中,我看到用戶名和密碼是以明文形式作爲基於行的文本數據(application/x-www-form-urlencoded)發送的。我知道這是不安全的,但它是這樣的。

+0

您是否嘗試設置內容類型? –

+0

是的,我試過但沒有幫助。事情是,當我在本地運行應用程序(本地主機)時根本沒有問題。實際上,我看到connection.connect()在Google App Engine上引發IOException。 – user1940909

回答

0

當您調用getOutputStream()時,連接已經隱式建立。沒有必要再次調用connection.connect()。

此外,不是關閉輸出寫入器,而是嘗試flush()。

最佳做法是,你應該在關閉,並在康涅狄格州finally塊:

InputStream in = null; 
OutputStream out = null; 
HttpUrlConnection conn = null; 

try { 
    ... 
} catch (IOException ioe) { 
    ... 
} finally { 
    if (in!=null) {try {in.close()} catch (IOException e) {}} 
    if (out!=null) {try {out.close()} catch (IOException e) {}} 
    if (conn!=null) {try {conn.close()} catch (IOException e) {}} 
} 
+0

好了,終於我解決了它。 @ d4n3所有信用給你,雖然上面的帖子並沒有直接解決問題,但你給了我一些有用的提示。 首先,一些句子是不必要的,在我重新編寫代碼後,我得到了異常「太多重定向」。我不得不手動管理重定向,而且我必須手動管理cookie(這就是爲什麼我可以在本地登錄但無法在GAE上登錄)。之後,一切正常。 – user1940909

相關問題