管理Android应用程序cookie
检查了许多类似的主题,但仍然找不到正确的答案 我正在尝试制作一个Android应用程序,用户登录并连接到服务器以检索一些数据。遗憾的是,我无法通过我需要应用程序来维护应用程序和服务器之间的会话的部分。只是不知道如何正确地做 据我阅读和理解,这个过程是这样的——用户单击登录按钮,向服务器发送请求。然后接收到响应,其中包含会话id为的cookie。我将会话id保存在SharedReferences中,以供以后使用。 当加载下一个活动时,我从SharedReferences中检索这个id,将它添加到下一个HTTP请求中,以便维护正确的会话。如果我错了,请纠正我 问题在于向HTTP请求添加会话id。为了保持应用程序和服务器之间的会话,即使应用程序被破坏,然后再次打开,下面的代码中应该更改什么?如何将cookie正确添加到请求中?看来我做得不对 我的代码如下:管理Android应用程序cookie,android,http,session,cookies,header,Android,Http,Session,Cookies,Header,检查了许多类似的主题,但仍然找不到正确的答案 我正在尝试制作一个Android应用程序,用户登录并连接到服务器以检索一些数据。遗憾的是,我无法通过我需要应用程序来维护应用程序和服务器之间的会话的部分。只是不知道如何正确地做 据我阅读和理解,这个过程是这样的——用户单击登录按钮,向服务器发送请求。然后接收到响应,其中包含会话id为的cookie。我将会话id保存在SharedReferences中,以供以后使用。 当加载下一个活动时,我从SharedReferences中检索这个id,将它添加到下
public class LoginScreen extends Activity {
DefaultHttpClient httpclient = new DefaultHttpClient();
SharedPreferences prefs;
Editor editor;
Button login_button;
String session_cookie;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
prefs = this.getSharedPreferences("filetitlehere", Context.MODE_PRIVATE);
editor = prefs.edit();
session_cookie = prefs.getString("sessionid", "not saved");
if (session_cookie != "not saved") {
// intent to another activity
} else {
login_button = (Button)findViewById(R.id.button_login);
login_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new Login().execute("http://mywebpage.com/login");
} else {
// error
}
}
});
}
}
private class Login extends AsyncTask<String, Void, String> {
protected String doInBackground(String... url) {
try {
return auth(url[0]);
} catch (IOException e) {
return "an error";
}
}
protected void onPostExecute(String result) {
JSONObject jsonobj;
Integer user_auth = 0;
try {
jsonobj = new JSONObject(result);
user_auth = jsonobj.getInt("auth");
} catch (JSONException e) {
// error
}
if (user_auth == 0) { // in case user not logged in
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
for (Cookie ck : cookies) {
if (ck.getName() == "PHPSESSID") {
// saved in SharedPreferences for later use
prefs.edit().putString("sessionid", ck.getValue().toString()).commit();
}
}
} else {
// user already logged in
Intent intent = new Intent(getApplicationContext(), HomeScreen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
}
private String auth(String myurl) throws IOException {
try {
HttpPost httppost = new HttpPost(myurl);
if (session_cookie == "not saved") {
// without adding cookie, cause cookie not saved in SharedPreferences
HttpResponse response = httpclient.execute(httppost);
} else {
// adding sessionid from SharedPreferences
BasicCookieStore cstore = new BasicCookieStore();
Cookie cookie = new BasicClientCookie("PHPSESSID",session_cookie);
cstore.addCookie(cookie);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cstore);
HttpResponse response = httpclient.execute(httppost, localContext);
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder resp = new StringBuilder();
String line = null;
while((line = bufferedReader.readLine()) != null){
resp.append(line);
}
return resp.toString();
} catch (UnsupportedEncodingException e) {
// error
} catch (ClientProtocolException e) {
// error
} catch (IOException e) {
// error
}
}
}
公共类登录屏幕扩展活动{
DefaultHttpClient httpclient=新的DefaultHttpClient();
共享引用优先权;
编辑;
按钮登录按钮;
字符串会话\u cookie;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u login\u屏幕);
prefs=this.getSharedReferences(“fileTitle”,Context.MODE_PRIVATE);
editor=prefs.edit();
session_cookie=prefs.getString(“sessionid”,“未保存”);
如果(会话_cookie!=“未保存”){
//意图从事另一项活动
}否则{
登录按钮=(按钮)findViewById(R.id.button\u登录);
登录按钮.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
ConnectivityManager connMgr=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_服务);
NetworkInfo NetworkInfo=connMgr.getActiveNetworkInfo();
if(networkInfo!=null&&networkInfo.isConnected()){
新建登录名()。执行(“http://mywebpage.com/login");
}否则{
//错误
}
}
});
}
}
私有类登录扩展异步任务{
受保护的字符串doInBackground(字符串…url){
试一试{
返回auth(url[0]);
}捕获(IOE异常){
返回“一个错误”;
}
}
受保护的void onPostExecute(字符串结果){
JSONObject jsonobj;
整数用户_auth=0;
试一试{
jsonobj=新的JSONObject(结果);
user_auth=jsonobj.getInt(“auth”);
}捕获(JSONException e){
//错误
}
如果(user_auth==0){//用户未登录
列表cookies=httpclient.getCookieStore().getCookies();
用于(Cookie ck:cookies){
if(ck.getName()=“PHPSESSID”){
//保存在SharedReferences中供以后使用
prefs.edit().putString(“sessionid”,ck.getValue().toString()).commit();
}
}
}否则{
//用户已登录
Intent Intent=新的Intent(getApplicationContext(),HomeScreen.class);
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK|intent.FLAG_ACTIVITY_CLEAR_TOP);
星触觉(意向);
}
}
}
私有字符串身份验证(字符串myurl)引发IOException{
试一试{
HttpPost HttpPost=新的HttpPost(myurl);
如果(会话_cookie==“未保存”){
//不添加cookie,导致cookie未保存在SharedReferences中
HttpResponse response=httpclient.execute(httppost);
}否则{
//从SharedReferences添加sessionid
BasicCookieStore cstore=新的BasicCookieStore();
Cookie Cookie=新的基本客户端Cookie(“PHPSESSID”,会话\u Cookie);
cstore.addCookie(cookie);
HttpContext localContext=新的BasicHttpContext();
setAttribute(ClientContext.COOKIE_存储,cstore);
HttpResponse response=httpclient.execute(httppost,localContext);
}
BufferedReader BufferedReader=新的BufferedReader(新的InputStreamReader(response.getEntity().getContent());
StringBuilder resp=新的StringBuilder();
字符串行=null;
而((line=bufferedReader.readLine())!=null){
分别追加(行);
}
return resp.toString();
}捕获(不支持的编码异常e){
//错误
}捕获(客户端协议例外e){
//错误
}捕获(IOE异常){
//错误
}
}
}
其他一些问题:
- 服务器是否仅在服务器端启动“session_start()”(例如,使用PHP)时(例如,当用户登录时)才发送会话id李>
- 如果服务器端的会话以某种方式被破坏,但我将以前保存的cookie添加到请求中,该怎么办?服务器在标题中理解并发回什么?会不会有另一个sessionid或者什么都没有
提前谢谢你 我问这个问题已经很久了。而不是编写会话管理mysel