2013-08-29 50 views
0

我正在寫一個客戶端j2me應用程序,它使用post方法連接到基於php的api。出於安全目的,應用程序和api應該在30分鐘超時的會話中進行交互。我的問題是,即使會話超時尚未完成,應用程序用戶也必須保持登錄狀態。我的php代碼很好,因爲我已經在瀏覽器上測試過了,它工作正常。但是,但應用程序失敗,我必須繼續登錄。我可能會錯過什麼?這些是使用我的Java應用程序發送到服務器的頭文件。成功的php會話需要什麼?

String phonenumber = this.phonenumberTextbox.getString(); 
String password = this.passwordTextBox.getString(); 
HttpConnection httpConn = null; 
String url = "http://192.168.56.1/?action=login-user"; 
InputStream is; 
OutputStream os; 
is = null; 
os = null; 
String sReply = ""; 
boolean loggedIn = false; 
try { 
    // Open an HTTP Connection object 
    httpConn = (HttpConnection) Connector.open(url); 
    // Setup HTTP Request to POST 
    httpConn.setRequestMethod(HttpConnection.POST); 
    httpConn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0"); 
    httpConn.setRequestProperty("Accept_Language", "en-US"); 
    //Content-Type is must to pass parameters in POST Request 
    httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
      os = httpConn.openOutputStream(); 
    String params; 
    params = "phonenumber=" + phonenumber + "&password=" + password; 
    os.write(params.getBytes()); 

    // Read Response from the Server 
    StringBuffer sb = new StringBuffer(); 
    is = httpConn.openDataInputStream(); 
    int chr; 
    while ((chr = is.read()) != -1) { 
     sb.append((char) chr); 
    } 
    // Web Server just returns stuff   
    sReply = sb.toString(); 
} catch (IOException ex) { 
    System.out.println("Cannot find server"); 
} finally { 
    if (is != null) { 
     try { 
      is.close(); 
     } catch (IOException ex) { 
     } 
    } 
    if (os != null) { 
     try { 
      os.close(); 
     } catch (IOException ex) { 
     } 
    } 
    if (httpConn != null) { 
     try { 
      httpConn.close(); 
     } catch (IOException ex) { 
     } 
    } 
} 
// do something with sReply 
+1

我認爲你錯過了Cookies(如果你在php中使用session_start(),你需要PHPSESSID cookie) – Christoph

回答

1

這些天在PHP中的默認實踐**在處理會話時如果爲PHP生成一個cookie以供客戶端存儲。您的Java客戶端必須存儲此cookie(默認情況下稱爲phpsessid,但任何值得使用的PHP程序員都會更改cookie名稱),並將其顯示在後續請求的HTTP標頭中。

我對Java中的HTTP支持不是很熟悉,但如果它像curl那樣,它將包含用於設置和檢索cookie的選項。

**在發出請求時,它曾經有可能通過查詢字符串(GET參數)傳遞會話標記,但由於這是非常不安全的並且泄露了潛在的敏感信息,所以它不再使用,甚至可能不會更長的時間作爲一個選項。