Java 安卓会话管理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4224913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android session management
提问by nala4ever
Is there a specific library for Android session management? I need to manage my sessions in a normal Android app. not in WebView
. I can set the session from my post method. But when I send another request that session is lost. Can someone help me with this matter?
是否有用于 Android 会话管理的特定库?我需要在普通的 Android 应用程序中管理我的会话。不在WebView
。我可以从我的 post 方法设置会话。但是当我发送另一个请求时,该会话丢失了。有人可以帮我解决这个问题吗?
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("My url");
HttpResponse response = httpClient.execute(httppost);
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
When I try to access the same host that session is lost:
当我尝试访问会话丢失的同一主机时:
HttpGet httpGet = new HttpGet("my url 2");
HttpResponse response = httpClient.execute(httpGet);
I get the login page response body.
我得到登录页面响应正文。
回答by CommonsWare
This has nothing to do with Android. It has everything to do with Apache HttpClient, the library you are using for HTTP access.
这与安卓无关。它与 Apache HttpClient(您用于 HTTP 访问的库)有关。
Session cookies are stored in your DefaultHttpClient
object. Instead of creating a new DefaultHttpClient
for every request, hold onto it and reuse it, and your session cookies will be maintained.
会话 cookie 存储在您的DefaultHttpClient
对象中。不要DefaultHttpClient
为每个请求创建一个新的,而是保留它并重用它,您的会话 cookie 将被维护。
You can read about Apache HttpClient hereand read about cookie management in HttpClient here.
回答by Jim
This is what I use for posts. I can use new httpClients
with this method where phpsessid
is the PHP
session id extracted from the login script using the code you have above.
这就是我用于帖子的内容。我可以httpClients
在此方法中使用 new ,其中使用上面的代码从登录脚本中提取phpsessid
的PHP
会话 ID是什么。
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("PHPSESSID",phpsessid));
回答by Yar
Generally, in Java HttpURLConnection you can set / get a cookie this way (here is the whole connection process). The code below is in my ConnectingThread's run(), from which all the connecting activity classes inherit. All share common static sCookie string which is sent with all the requests. Therefore you can maintain a common state like being logged on / off:
通常,在 Java HttpURLConnection 中,您可以通过这种方式设置/获取 cookie(这里是整个连接过程)。下面的代码在我的 ConnectingThread 的 run() 中,所有连接的活动类都从它继承。所有共享公共静态 sCookie 字符串,该字符串随所有请求一起发送。因此,您可以保持一个常见的状态,例如登录/注销:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//set cookie. sCookie is my static cookie string
if(sCookie!=null && sCookie.length()>0){
conn.setRequestProperty("Cookie", sCookie);
}
// Send data
OutputStream os = conn.getOutputStream();
os.write(mData.getBytes());
os.flush();
os.close();
// Get the response!
int httpResponseCode = conn.getResponseCode();
if (httpResponseCode != HttpURLConnection.HTTP_OK){
throw new Exception("HTTP response code: "+httpResponseCode);
}
// Get the data and pass them to the XML parser
InputStream inputStream = conn.getInputStream();
Xml.parse(inputStream, Xml.Encoding.UTF_8, mSaxHandler);
inputStream.close();
//Get the cookie
String cookie = conn.getHeaderField("set-cookie");
if(cookie!=null && cookie.length()>0){
sCookie = cookie;
}
/* many cookies handling:
String responseHeaderName = null;
for (int i=1; (responseHeaderName = conn.getHeaderFieldKey(i))!=null; i++) {
if (responseHeaderName.equals("Set-Cookie")) {
String cookie = conn.getHeaderField(i);
}
}*/
conn.disconnect();
回答by user344293
Totally transparent way to keep a session active (user logged in , or whatever) in Android apps. It uses the apache DefaultHttpClient inside a Singleton and a HttpRequest/Response Interceptors.
在 Android 应用程序中保持会话处于活动状态(用户登录或其他)的完全透明的方式。它在 Singleton 和 HttpRequest/Response Interceptors 中使用 apache DefaultHttpClient。
The SessionKeeper class simply checks whether one of the headers is Set-Cookie, and if it does, it simply remembers it. The SessionAdder simply adds the session id to the request (if not null). This way, you the whole authentication process is totally transparent.
SessionKeeper 类只是检查头之一是否是 Set-Cookie,如果是,它会简单地记住它。SessionAdder 只是将会话 ID 添加到请求中(如果不为空)。这样,您整个身份验证过程是完全透明的。
public class HTTPClients {
private static DefaultHttpClient _defaultClient;
private static String session_id;
private static HTTPClients _me;
private HTTPClients() {
}
public static DefaultHttpClient getDefaultHttpClient(){
if ( _defaultClient == null ) {
_defaultClient = new DefaultHttpClient();
_me = new HTTPClients();
_defaultClient.addResponseInterceptor(_me.new SessionKeeper());
_defaultClient.addRequestInterceptor(_me.new SessionAdder());
}
return _defaultClient;
}
private class SessionAdder implements HttpRequestInterceptor {
@Override
public void process(HttpRequest request, HttpContext context)
throws HttpException, IOException {
if ( session_id != null ) {
request.setHeader("Cookie", session_id);
}
}
}
private class SessionKeeper implements HttpResponseInterceptor {
@Override
public void process(HttpResponse response, HttpContext context)
throws HttpException, IOException {
Header[] headers = response.getHeaders("Set-Cookie");
if ( headers != null && headers.length == 1 ){
session_id = headers[0].getValue();
}
}
}
}