2011-04-17 112 views
8

嗨,大家好,我有幾個關於在Android中實現登錄功能的問題。Android HTTP登錄問題

1. Does android have anything like sessions or cookies?我應該如何「記住」用戶是否在使用?顯然,我不想每次使用我的應用程序時都要求輸入密碼!

2. Should I hash the password before sending it to the server?我在我的數據庫中有一個用戶名和密碼列的表。當我想檢查登錄時,是否應該在執行身份驗證之前將密碼散列發送到服務器,如login.php?u=sled&p=34819d7beeabb9260a5c854bc85b3e44或只是純文本如login.php?u=sled&p=mypassword並在服務器上散列它?

回答

10

Android有沒有類似會話或cookie的東西?

是的。有兩種選擇。

選項#1:

您可以使用CookieManager設置你的cookie。

選項#2:

另一種方法(我用我的應用程序一個這種替代)就是抓住你的cookie您發送您的用戶名和密碼後,服務器(例如,通過HttpPostHttpGet)。在你的問題中,你使用$_GET風格的登錄驗證,所以我的示例代碼將使用HttpGet。使用HttpGet

示例代碼:

HttpParams httpParams = new BasicHttpParams(); 

// It's always good to set how long they should try to connect. In this 
// this example, five seconds. 
HttpConnectionParams.setConnectionTimeout(httpParams, 5000); 
HttpConnectionParams.setSoTimeout(httpParams, 5000); 

DefaultHttpClient postClient = new DefaultHttpClient(httpParams);   
// Your url using $_GET style. 
final String url = "www.yourwebsite.com/login.php?u=myusername&p=mypassword"; 
HttpGet httpGet = new HttpGet(url); 
HttpResponse response; 

try { 
    // Execute your HttpGet against the server and catch the response to our 
    // HttpResponse. 
    response = postClient.execute(httpGet); 

    // Check if everything went well. 
    if(response.getStatusLine().getStatusCode() == 200) { 
     // If so, grab the entity.   
     HttpEntity entity = response.getEntity(); 

     // If entity isn't null, grab the CookieStore from the response. 
     if (entity != null) { 
      CookieStore cookies = postClient.getCookieStore(); 
      // Do some more stuff, this should probably be a method where you're 
      // returning the CookieStore.  
     }     
    } 

} catch (Exception e) { 
} 

現在,當你有你的CookieStore;從中獲取一個cookie列表,然後你可以使用Cookie來確定名稱,域名,值等等。

下一次你嘗試訪問你的網站的「鎖定」內容;從您的Cookie信息設置cookie到您的HttpURLConnection

URL url = new URL("www.yourwebsite.com/lockedcontent.php"); 

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 

httpURLConnection.setInstanceFollowRedirects(false); 
// "Host" and "Cookie" are fields in the HTTP response. Use WireShark 
// via your computer to determine correct header names. 
httpURLConnection.setRequestProperty("Host", domainOfYourCookie); 
httpURLConnection.setRequestProperty("Cookie", valueOfYourCookie); 

final int responseCode = httpURLConnection.getResponseCode(); 

// And get the content... 

我應該把它發送到服務器之前散列密碼?

取決於您的系統是如何設計的。發送到服務器時必須有正確的信息。這也取決於你如何在你的.php文件中散列你的信息。

我應該怎樣「記住」用戶是否被偷懶?

將信息存儲在SharedPreferences或其他東西。就像我之前說過的,如果你的登錄系統設計正確,你可以對它進行哈希 - 這取決於你如何在你的.php文件中對它進行哈希處理。