【问题标题】:android how to maintain sessionandroid如何维护会话
【发布时间】:2015-03-28 14:42:48
【问题描述】:
我正在 android 中构建一个登录应用程序,在该应用程序中,我点击了一个 url(带有用户名和密码)直到该部分它工作正常,但之后每当我点击一个 url(一旦用户通过身份验证),它什么都不返回(即,请先登录之类的错误消息)。
我发现这是 phpSessionId 的错误(即会话被销毁以供进一步请求),如果我们希望我们的 Android 应用程序在服务器端保持身份验证,我们需要在第一次连接后获取该 id 然后发送它在我们所有后续请求的标头中。
但问题是我无法从第一个连接的标头中获取 sessionId 并将其与进一步的请求一起发送。
请给我一些代码或链接以正确完成任务。谢谢。
【问题讨论】:
标签:
php
android
web-services
session-cookies
【解决方案1】:
最后我解决了 Android 中的会话处理问题。 Android 不能处理会话本身(一个简单的浏览器可以)所以我们必须明确地处理它。我稍微更改了 http 连接的代码。建立连接时在第一个 Activity 中创建 DefaultHttpClient 的实例
public static DefaultHttpClient httpClient;
第一次连接,我做了以下操作:
公共类 ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = MainActivity.httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = MainActivity.httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
并按以下方式调用
jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
这也将帮助我解决 Android 中的会话问题。