android获取web服务器端session并验证登陆 一

来源:互联网 发布:小米 数据分析岗位 编辑:程序博客网 时间:2024/05/24 04:19

传统网页实现用户登陆一般采用session或cookie记录用户基本信息又或者两者结合起来使用。android也可以采用session实现用户登陆验证并记录用户登陆状态时的基本信息,session是在服务器端的;而类似cookie的记录方式,则可以在客户端采用xml文件记录用户基本信息,重要数据则可以加密存放客户端。android实现的session登陆功能与网页请求不同的是,网页形式的一次成功的登陆请求后,再点击其他页面时,session一直是存在的,在一定时间内是有效的;而采用android客户端请求的一次成功登陆后,再次发送新的请求,则会产生新的session,而不是原来的。这就需要记录session的id号,并在整个请求过程中都记录并传递这个id号,才能保证 session的一致性。

以获取php session为例,主要思路实现分为客户端与服务器端3个步骤。
1.)客户端(Android

建立一个名为GetWebSession的android项目,编写GetWebSession.java,LoginSuccessActivity.java,GetUserInfoActivity.java三个activity类。

1. GetWebSession.java主要是实现布局界面以及发送用户名和密码到php服务器端验证,如果验证成功则跳转到 LoginSuccessActivity.java类。GetWebSession.java主要涉及到与服务器端连接请求,对从服务器端返回的 json数据(如用户id,session等)进行解析,并存入HashMap,传递到LoginSuccessActivity.java

代码如下:

  1. package com.login.main;

  2. import java.io.IOException;

  3. 。。。。

  4. import android.view.View.OnClickListener;
  5. import android.widget.Button;
  6. import android.widget.EditText;
  7. import android.widget.Toast;

  8. public class GetWebSession extends Activity {
  9. /** Called when the activity is first created. */

  10. private EditText user;
  11. private EditText password;
  12. private Button loginBtn;
  13. private Button logoutBtn;

  14. //主要是记录用户会话过程中的一些用户的基本信息

  15. private HashMap<String, String> session =new HashMap<String, String>();

  16. @Override

  17. public void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.main);

  20. user=(EditText)findViewById(R.id.user);
  21. password=(EditText)findViewById(R.id.password);
  22. loginBtn=(Button)findViewById(R.id.loginBtn);
  23. loginBtn.setOnClickListener(loginClick);
  24. logoutBtn=(Button)findViewById(R.id.logoutBtn);
  25. logoutBtn.setOnClickListener(logoutClick);
  26. }

  27. OnClickListener loginClick=new OnClickListener() {

  28. @Override
  29. public void onClick(View v) {
  30. // TODO Auto-generated method stub
  31. if(checkUser()){
  32. Toast.makeText(v.getContext(), "用户登录成功!", Toast.LENGTH_SHORT).show();
  33. Context context = v.getContext();
  34. Intent intent = new Intent(context,
  35. LoginSuccessActivity.class);

  36. //传递session参数,在用户登录成功后为session初始化赋值,即传递HashMap的值

  37. Bundle map = new Bundle();
  38. map.putSerializable("sessionid", session);
  39. intent.putExtra("session", map);
  40. context.startActivity(intent); // 跳转到成功页面
  41. }

  42. else
  43. Toast.makeText(v.getContext(), "用户验证失败!", Toast.LENGTH_SHORT).show();
  44. }
  45. };

  46. OnClickListener logoutClick=new OnClickListener() {
  47. @Override
  48. public void onClick(View v) {
  49. // TODO Auto-generated method stub
  50. System.exit(0);

  51. }

  52. };

  53. private boolean checkUser(){
  54. String username=user.getText().toString();

  55. String pass=password.getText().toString();

  56. DefaultHttpClient mHttpClient = new DefaultHttpClient();

  57. HttpPost mPost = new HttpPost("http://10.0.2.2/web/php/login.php");

  58. //传递用户名和密码相当于

  59. //http://10.0.2.2/web/php/login.php?username=''&password=''

  60. List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();

  61. pairs.add(new BasicNameValuePair("username", username));

  62. pairs.add(new BasicNameValuePair("password", pass));

  63. try {

  64. mPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));

  65. } catch (UnsupportedEncodingException e) {

  66. // TODO Auto-generated catch block

  67. e.printStackTrace();

  68. }

  69. try {

  70. HttpResponse response = mHttpClient.execute(mPost);

  71. int res = response.getStatusLine().getStatusCode();

  72. if (res == 200) {

  73. HttpEntity entity = response.getEntity();

  74. if (entity != null) {

  75. String info = EntityUtils.toString(entity);

  76. System.out.println("info-----------"+info);

  77. //以下主要是对服务器端返回的数据进行解析

  78. JSONObject jsonObject=null;

  79. //flag为登录成功与否的标记,从服务器端返回的数据

  80. String flag="";

  81. String name="";

  82. String userid="";

  83. String sessionid="";

  84. try {

  85. jsonObject = new JSONObject(info);

  86. flag = jsonObject.getString("flag");

  87. name = jsonObject.getString("name");

  88. userid = jsonObject.getString("userid");

  89. sessionid = jsonObject.getString("sessionid");

  90. } catch (JSONException e) {

  91. // TODO Auto-generated catch block

  92. e.printStackTrace();

  93. }

  94. //根据服务器端返回的标记,判断服务端端验证是否成功

  95. if(flag.equals("success")){

  96. //为session传递相应的值,用于在session过程中记录相关用户信息

  97. session.put("s_userid", userid);

  98. session.put("s_username", name);

  99. session.put("s_sessionid", sessionid);

  100. return true;

  101. }

  102. else{

  103. return false;

  104. }

  105. }

  106. else{

  107. return false;

  108. }

  109. }

  110. } catch (ClientProtocolException e) {

  111. // TODO Auto-generated catch block

  112. e.printStackTrace();

  113. } catch (IOException e) {

  114. // TODO Auto-generated catch block

  115. e.printStackTrace();

  116. }

  117. return false;

  118. }

  119. }

复制代码
2. LoginSuccessActivity.java
主要获取php的session唯一的标识id以及用户的一些基本信息,session id则作为本次用户登录状态在服务器的唯一标识,即确定用户的唯一状态进行相关操作。LoginSuccessActivity.java类的方法与 GetWebSession.java类似。其主要功能是获取session id后再次发送session id到服务器进行验证,根据封装的session数据验证用户操作权限等。

  1. package com.login.main;
  2. import java.io.IOException;
  3. import java.io.UnsupportedEncodingException;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import org.apache.http.HttpEntity;
  8. import org.apache.http.HttpResponse;
  9. import org.apache.http.client.ClientProtocolException;
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;
  11. import org.apache.http.client.methods.HttpPost;
  12. import org.apache.http.impl.client.DefaultHttpClient;
  13. import org.apache.http.message.BasicNameValuePair;
  14. import org.apache.http.protocol.HTTP;
  15. import org.apache.http.util.EntityUtils;
  16. import org.json.JSONException;
  17. import org.json.JSONObject;
  18. import android.app.Activity;
  19. import android.content.Context;
  20. import android.content.Intent;
  21. import android.os.Bundle;
  22. import android.view.View;
  23. import android.view.View.OnClickListener;
  24. import android.widget.Button;
  25. import android.widget.TextView;
  26. import android.widget.Toast;
  27. public class LoginSuccessActivity extends Activity{
  28. private HashMap&lt;String, String&gt;session;
  29. @SuppressWarnings("unchecked")
  30. @Override
  31. protected void onCreate(Bundle savedInstanceState) {
  32. // TODO Auto-generated method stub
  33. super.onCreate(savedInstanceState);
  34. setContentView(R.layout.login_success);
  35. //获取从登录成功后界面的传递的参数
  36. session =&nbsp; (HashMap&lt;String, String&gt;) this.getIntent()
  37. .getBundleExtra("session").getSerializable("sessionid");
  38. //读取session的基本信息,并显示相应的控件
  39. String userid_info=session.get("s_userid");
  40. String username_info=session.get("s_username");
  41. String session_id=session.get("s_sessionid");
  42. //显示相应的内容到控件
  43. TextView userid_show=(TextView)findViewById(R.id.userid_show);
  44. userid_show.setText(userid_info);
  45. TextView username_show=(TextView)findViewById(R.id.username_show);
  46. username_show.setText(username_info);
  47. TextView sessionid_show=(TextView)findViewById(R.id.sessionid_show);
  48. sessionid_show.setText(session_id);
  49. //根据本次session再次获取用户信息
  50. Button getInfo=(Button)findViewById(R.id.getinfo);
  51. getInfo.setOnClickListener(getInfoClick);
  52. }
  53. OnClickListener getInfoClick=new OnClickListener() {
  54. @Override
  55. public void onClick(View v) {
  56. // TODO Auto-generated method stub
  57. if(getUserInfo()){
  58. Context context = v.getContext();
  59. Intent intent = new Intent(context,
  60. GetUserInfoActivity.class);
  61. //传递session参数,在用户登录成功后为session初始化赋值,即传递HashMap的值
  62. Bundle map = new Bundle();
  63. map.putSerializable("sessionid", session);
  64. intent.putExtra("session", map);
  65. context.startActivity(intent); // 跳转到成功页面
  66. }else{
  67. Toast.makeText(v.getContext(), "数据为空!", Toast.LENGTH_SHORT).show();
  68. }
  69. }
  70. };
  71. private boolean getUserInfo(){
  72. String sess_username=session.get("s_username");
  73. String sess_userid=session.get("s_userid");
  74. String sess_id=session.get("s_sessionid");
  75. DefaultHttpClient mHttpClient = new DefaultHttpClient();
  76. HttpPost mPost = new HttpPost("http://10.0.2.2/web/php/getinfo.php");
  77. List&lt;BasicNameValuePair&gt; pairs = new ArrayList&lt;BasicNameValuePair&gt;();
  78. pairs.add(new BasicNameValuePair("sess_userid", sess_userid));
  79. pairs.add(new BasicNameValuePair("sess_username", sess_username));
  80. pairs.add(new BasicNameValuePair("sess_sessionid", sess_id));
  81. try {
  82. mPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
  83. } catch (UnsupportedEncodingException e) {
  84. // TODO Auto-generated catch block
  85. e.printStackTrace();
  86. }
  87. try {
  88. HttpResponse response = mHttpClient.execute(mPost);
  89. int res = response.getStatusLine().getStatusCode();
  90. if (res == 200) {
  91. HttpEntity entity = response.getEntity();
  92. if (entity != null) {
  93. String info = EntityUtils.toString(entity);
  94. System.out.println("info-----------"+info);
  95. //以下主要是对服务器端返回的数据进行解析
  96. JSONObject jsonObject=null;
  97. //flag为登录成功与否的标记,从服务器端返回的数据
  98. String flag="";
  99. String userinfo="";
  100. String level="";
  101. String sessionid="";
  102. try {
  103. jsonObject = new JSONObject(info);
  104. flag = jsonObject.getString("flag");
  105. userinfo = jsonObject.getString("info");
  106. level = jsonObject.getString("level");
  107. sessionid = jsonObject.getString("sessionid");
  108. } catch (JSONException e) {
  109. // TODO Auto-generated catch block
  110. e.printStackTrace();
  111. }
  112. //根据服务器端返回的标记,判断服务端端验证是否成功
  113. if(flag.equals("notempty")){
  114. //为session传递相应的值,用于在session过程中记录相关用户信息
  115. session.put("info_userinfo", userinfo);
  116. session.put("info_level", level);
  117. session.put("info_sessionid", sessionid);
  118. return true;
  119. }
  120. else{
  121. return false;
  122. }
  123. }
  124. else{
  125. return false;
  126. }
  127. }
  128. } catch (ClientProtocolException e) {
  129. // TODO Auto-generated catch block
  130. e.printStackTrace();
  131. } catch (IOException e) {
  132. // TODO Auto-generated catch block
  133. e.printStackTrace();
  134. }
  135. return false;
  136. }
  137. }
复制代码
3.GetUserInfoActivity.java类是根据用户登录后产生唯一session 标识进行操作获取用户详细信息的类。

  1. package com.login.main;
  2. import java.util.HashMap;
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.widget.TextView;
  6. public class GetUserInfoActivity extends Activity{
  7. private HashMap&lt;String, String&gt;session;
  8. @SuppressWarnings("unchecked")
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. // TODO Auto-generated method stub
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.get_info);
  14. //获取从登录成功后界面的再次传递的参数
  15. session =&nbsp; (HashMap&lt;String, String&gt;) this.getIntent().
  16. getBundleExtra("session").getSerializable("sessionid");
  17. //读取session的基本信息,并显示相应的控件
  18. String session_info=session.get("info_userinfo");
  19. String session_level=session.get("info_level");
  20. String session_id=session.get("info_sessionid");
  21. //显示相应的内容到控件
  22. System.out.println("session_info--------"+session_info);
  23. TextView get_info=(TextView)findViewById(R.id.get_info);
  24. get_info.setText(session_info);
  25. TextView get_level=(TextView)findViewById(R.id.get_level);
  26. get_level.setText(session_level);
  27. TextView get_sessionid=(TextView)findViewById(R.id.get_sessionid);
  28. get_sessionid.setText(session_id);
  29. }
  30. }
复制代码
4.三个布局的xml文件
(1.)main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent" >
  6. <TextView android:layout_height="wrap_content"
  7. android:layout_width="wrap_content"
  8. android:text="用户"></TextView>
  9. <EditText android:layout_height="wrap_content"
  10. android:text="" android:layout_width="fill_parent"
  11. android:singleLine="true" android:id="@+id/user"&nbsp; ></EditText>
  12. <TextView android:layout_height="wrap_content"&nbsp;
  13. android:layout_width="wrap_content"
  14. android:text="密码"></TextView>
  15. <EditText android:id="@+id/password"
  16. android:layout_height="wrap_content"
  17. android:text="" android:layout_width="fill_parent"
  18. android:password="true" android:singleLine="true"></EditText>
  19. <LinearLayout android:layout_height="wrap_content"&nbsp;
  20. android:layout_width="fill_parent"
  21. android:orientation="horizontal"
  22. android:paddingLeft="0dip">
  23. <TableRow android:layout_width="fill_parent"
  24. android:layout_height="wrap_content">
  25. <Button android:layout_height="fill_parent"
  26. android:layout_width="fill_parent" android:text="登录"
  27. android:id="@+id/loginBtn"
  28. android:layout_weight="1"></Button>
  29. <Button android:layout_height="fill_parent"
  30. android:layout_width="fill_parent"
  31. android:text="退出"&nbsp;
  32. android:id="@+id/logoutBtn"
  33. android:layout_weight="1"></Button>
  34. </TableRow> </LinearLayout> </LinearLayout>
复制代码
(2.)login_success.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent" android:layout_height="fill_parent"
  4. android:orientation="vertical">
  5. <LinearLayout android:layout_height="wrap_content"&nbsp;
  6. android:layout_width="fill_parent"
  7. android:orientation="horizontal"
  8. android:paddingLeft="0dip">
  9. <TextView
  10. android:layout_height="fill_parent"
  11. android:layout_width="wrap_content"
  12. android:text="用户ID:"&nbsp;&nbsp; >
  13. </TextView>
  14. <TextView android:layout_height="fill_parent"
  15. android:layout_width="fill_parent"
  16. android:text=""&nbsp;
  17. android:id="@+id/userid_show" ></TextView>
  18. </LinearLayout>
  19. <LinearLayout android:layout_height="wrap_content"&nbsp;
  20. android:layout_width="fill_parent"
  21. android:orientation="horizontal"
  22. android:paddingLeft="0dip">
  23. <TextView android:layout_height="fill_parent"
  24. android:layout_width="wrap_content"
  25. android:text="用户名: "&nbsp;&nbsp; ></TextView>
  26. <TextView android:layout_height="fill_parent"
  27. android:layout_width="fill_parent"
  28. android:text=""&nbsp;
  29. android:id="@+id/username_show" ></TextView>
  30. </LinearLayout>
  31. <LinearLayout android:layout_height="wrap_content"&nbsp;
  32. android:layout_width="fill_parent"
  33. android:orientation="horizontal"
  34. android:paddingLeft="0dip">
  35. <TextView android:layout_height="fill_parent"
  36. android:layout_width="wrap_content"
  37. android:text="本次会话:"&nbsp;&nbsp; ></TextView>
  38. <TextView android:layout_height="fill_parent"
  39. android:layout_width="fill_parent"
  40. android:text=""&nbsp;
  41. android:id="@+id/sessionid_show" ></TextView>
  42. </LinearLayout>
  43. <LinearLayout android:layout_height="wrap_content"&nbsp;
  44. android:layout_width="fill_parent"
  45. android:orientation="horizontal"
  46. android:paddingLeft="0dip">
  47. <Button android:layout_height="fill_parent"
  48. android:layout_width="wrap_content"
  49. android:id="@+id/getinfo"
  50. android:text="根据本次会话再次获取用户信息"&nbsp;&nbsp;
  51. ></Button>
  52. </LinearLayout>
  53. </LinearLayout>
复制代码
(3.)get_info.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical">
  6. <LinearLayout android:layout_height="wrap_content"&nbsp;
  7. android:layout_width="fill_parent"
  8. android:orientation="horizontal"
  9. android:paddingLeft="0dip">
  10. <TextView android:layout_height="fill_parent"
  11. android:layout_width="wrap_content"
  12. android:text="用户信息: "&nbsp;&nbsp; >
  13. </TextView>
  14. <TextView android:layout_height="fill_parent"
  15. android:layout_width="fill_parent"
  16. android:text=""&nbsp;
  17. android:id="@+id/get_info" ></TextView>
  18. </LinearLayout>
  19. <LinearLayout android:layout_height="wrap_content"&nbsp;
  20. android:layout_width="fill_parent"
  21. android:orientation="horizontal"
  22. android:paddingLeft="0dip">
  23. <TextView android:layout_height="fill_parent"
  24. android:layout_width="wrap_content"
  25. android:text="用户级别:"&nbsp;&nbsp; ></TextView>
  26. <TextView android:layout_height="fill_parent"
  27. android:layout_width="fill_parent"
  28. android:text=""&nbsp;
  29. android:id="@+id/get_level" ></TextView>
  30. </LinearLayout>
  31. <LinearLayout android:layout_height="wrap_content"
  32. android:layout_width="fill_parent"
  33. android:orientation="horizontal"
  34. android:paddingLeft="0dip">
  35. <TextView android:layout_height="fill_parent"
  36. android:layout_width="wrap_content"
  37. android:text="本次会话:"&nbsp;&nbsp; ></TextView>
  38. <TextView android:layout_height="fill_parent"
  39. android:layout_width="fill_parent" android:text=""&nbsp;
  40. android:id="@+id/get_sessionid" ></TextView>
  41. </LinearLayout>
  42. <LinearLayout android:layout_height="wrap_content"&nbsp;
  43. android:layout_width="fill_parent"
  44. android:orientation="horizontal"
  45. android:paddingLeft="0dip"> </LinearLayout> </LinearLayout>
原创粉丝点击