gpt4 book ai didi

Android HTTP登录问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:33:55 25 4
gpt4 key购买 nike

我正在 Android 中实现登录功能。

  1. android 有 session 或 cookie 之类的东西吗?我应该如何“记住”用户已登录?显然我不想每次使用我的应用程序时都要求输入密码!

  2. 我应该在将密码发送到服务器之前对其进行哈希处理吗?我的数据库中有一个表,其中包含用户和密码列。当我想检查登录时,我应该将哈希密码发送到服务器,如 login.php?u=sled&p=34819d7beeabb9260a5c854bc85b3e44,还是像 login.php?u=sled&p 这样的纯文本=mypassword 并在我执行身份验证之前在服务器上散列它?

最佳答案

Does android have anything like sessions or cookies?

是的。有两种选择。

选项#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 信息中为您的 HttpURLConnection 设置一个 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...

Should I hash the password before sending it to the server?

取决于您的系统是如何设计的。将其发送到您的服务器时,您必须具有正确的信息。这也取决于您如何在 .php 文件中散列信息。

How should I 'remember' that the user is loged in?

将信息存储在 SharedPreferences 或其他内容中。正如我之前所说,如果您的登录系统设计正确,您可以对它进行哈希处理——这取决于您在 .php 文件中对其进行哈希处理的方式。

关于Android HTTP登录问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5690637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com