Android HTTP登录问题

时间:2011-04-17 00:36:24

标签: android http authentication login

嘿伙计们,我有几个关于在Android中实现登录功能的问题。

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之类的纯文本并在执行身份验证之前将其哈希在服务器上?

1 个答案:

答案 0 :(得分:9)

  

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来确定名称,域名,值等...

下次您尝试访问网站的“锁定”内容时;从您的HttpURLConnection信息中为您的Cookie设置Cookie:

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文件中如何对其进行哈希处理。