2012-07-29 77 views
5

我想爲我的android應用程序做一個登錄腳本,腳本將發送我的電子郵件和密碼到PHP服務器,驗證登錄,然後創建一個PHP會話,以便用戶停留登錄。這是我的代碼,使用PHP會話與我的Android應用程序登錄

HttpPost httppost = new HttpPost("http://server.com/login.php"); 
// Create a new HttpClient and Post Header 
HttpClient httpclient = new DefaultHttpClient(); 

public String login() { 

    String userID = ""; 

    try { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("email", "[email protected]")); 
     nameValuePairs.add(new BasicNameValuePair("password", "admin")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     // Execute HTTP Post Request 
     HttpResponse response = httpclient.execute(httppost); 

     userID = EntityUtils.toString(response.getEntity()); 
     //Log.v("Login response", "" + userID); 



    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 

    return userID; 
} 

這個腳本成功地將數據發送到我的服務器和我的PHP成功登錄的用戶。我已經放置了「HttpClient httpclient = new DefaultHttpClient();」我的主要登錄方法之外。這有助於存儲會話,直到我呼叫另一個班級,然後再重新設置會話。所以我想知道如何改變代碼,以便「httpclient」以某種方式存儲,這樣我可以保持會話並保持登錄到我的服務器。謝謝!

+0

我想你可以保存的SessionID在'SharedPreferences'每次你需要發送一次請求剛剛從那裏 – monim 2015-11-06 15:22:57

回答

3

Android Http get Session Cookie

獲取cookie的會話ID,並使用該Cookie在未來的請求到服務器。

+0

得到它謝謝,但是如何保存Header變量以便我可以輕鬆地從所有類中訪問它? – rusty009 2012-08-01 18:33:18

+0

你可以傳遞一個擁有該變量信息的全局對象嗎? 試試看這個想法的例子... http://www.javaworld.com/javaqa/2000-05/03-qa-0526-pass.html – 2012-08-02 14:03:08

2

另一種方法是讓你的php代碼在login.response響應一個字符串包含session_id讓android應用程序檢索這個id並存儲它。今後的任何請求可以通過使用POST方法與sess_id進行=存儲ID

<?php 
if(isset($_POST['sess_id'])) 
{ 
session_id($_POST['sess_id']); //starts session with given session id 
session_start(); 
$_SESSION['count']++; 
} 
else { 
session_start(); //starts a new session 
$_SESSION['count']=0; 
} 
echo session_id(); 
?> 
+0

你想寫一個例子說明你如何使用一個請求到服務器,那麼你已經有會話ID? – Vinigas 2016-10-20 18:45:35

相關問題