[英]Android: Keeping session alive on remote server between Activities
我在iOS中内置了另一个应用程序,当用户登录该应用程序时,服务器会在该会话中将其登录。 在iOS应用程序中,只要正常会话和来自该应用程序的所有请求都看到该人仍在登录,该会话就会保持活动状态。
我以为这与Android应用程序相同,但是登录后我切换到下一个活动,然后向服务器发送请求以填充页面。 我返回的结果是用户未登录。
我不了解这里是否存在使我的会话无法保持在服务器上的情况吗?
我有一个我的所有Activity都扩展的基类,在基类内部我有这个受保护的类。 我用它发送所有请求。
protected class API extends AsyncTask <Void, Void, String>
{
public String RequestName;
public String RequestType;
public String RequestUrl;
public List<NameValuePair> RequestParameters;
public API(String Name, String Type, String Url, List<NameValuePair> params)
{
RequestName = Name;
RequestType = Type;
RequestUrl = Url;
RequestParameters = params;
}
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException
{
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0)
{
byte[] b = new byte[4096];
n = in.read(b);
if (n>0)
out.append(new String(b, 0, n));
}
return out.toString();
}
@Override
protected String doInBackground(Void... params)
{
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String text = null;
if(RequestType == "post")
{
HttpPost p = new HttpPost("http://www.ehrx.com/api/" + RequestUrl);
try
{
p.setEntity(new UrlEncodedFormEntity(RequestParameters));
HttpResponse response = httpClient.execute(p, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
}
catch (Exception e)
{
return e.getLocalizedMessage();
}
}
else
{
HttpGet httpGet = new HttpGet("http://www.ehrx.com/api/" + RequestUrl);
try
{
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
}
catch (Exception e)
{
return e.getLocalizedMessage();
}
}
return text;
}
protected void onPostExecute(String results)
{
HandleResult(results, RequestName);
}
}
我想会话在服务器上仍然有效,但是您在Android应用中丢失了会话cookie。 看起来您正在为每个请求创建一个新的客户端和一个新的上下文。 您将需要为上下文设置cookie存储,以便它可以使用您先前通过身份验证的请求中的会话cookie。 如何使用Android和/或Java中的HttpClient管理cookie的答案? 应该给您更多信息。
使用singleton类可以轻松解决此问题(您应在所有http请求中使用相同的HTTP客户端)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.