android 之手机客户端登陆

本文介绍了一个使用Android客户端向服务器发起登录请求的示例。详细展示了如何通过GET和POST方式发送登录请求并验证登录状态。

今天要学的例子是通过android 手机客户端登陆到服务器。验证是否登陆成功。

首先:我们在myEclipse 中新建一个web项目提供手机客户端的登陆请求,并做出响应,我们使用struts2.1.8。做一个简单的示例。

这个web服务可以接收post |get 的请求。代码如下:

[java]  view plain copy
  1. package com.hkrt.action;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6. import java.util.ArrayList;  
  7. import java.util.HashMap;  
  8. import java.util.List;  
  9. import java.util.Map;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12. import org.apache.struts2.ServletActionContext;  
  13. import com.opensymphony.xwork2.Action;  
  14. public class LoginCheckAction implements Action{    
  15.         
  16.     private String userName;    
  17.     private String password;    
  18.         
  19.     public String execute() throws Exception {    
  20.             
  21.         HttpServletRequest request = ServletActionContext.getRequest();    
  22.         InputStream is = request.getInputStream();  
  23.         byte [] result = readIS(is);  
  24.         if(result.length>0){  
  25.              Map<String,String> resuestMap = getRequestParams(new String(result));  
  26.              if(!resuestMap.isEmpty()){  
  27.                  userName = resuestMap.get("userName");  
  28.                  password = resuestMap.get("password");  
  29.              }    
  30.         }else{  
  31.               userName = request.getParameter("userName");    
  32.               password = request.getParameter("password");    
  33.         }  
  34.         System.out.println("userName:"+userName+"\tpassword:"+password);  
  35.         HttpServletResponse response = ServletActionContext.getResponse();    
  36.         OutputStream os = response.getOutputStream();      
  37.         if(!"zs".equals(userName) || !"123".equals(password)){    
  38.             os.write(new String("-1").getBytes());    
  39.         } else {    
  40.             os.write(new String("1").getBytes());    
  41.         }    
  42.             
  43.         response.setStatus(HttpServletResponse.SC_OK);    
  44.         System.out.println("数据访问");  
  45.           
  46.         
  47.         return null;    
  48.     
  49.     }    
  50.     public static byte[] readIS(InputStream is) throws IOException {  
  51.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  52.         byte[] buff = new byte[1024];  
  53.         int length = 0;  
  54.         while ((length = is.read(buff)) != -1) {  
  55.             bos.write(buff, 0, length);  
  56.         }  
  57.         return bos.toByteArray();  
  58.     }  
  59.     // 以Post 请求时,返回请求一个map的请求参数  
  60.     private Map<String,String> getRequestParams(String requestStr){  
  61.         Map<String,String> maps = new HashMap<String, String>();  
  62.         String [] strs = requestStr.split("&");  
  63.         List<String> list = new ArrayList<String>();  
  64.         for(String st:strs){  
  65.             list.add(st);  
  66.         }  
  67.         for(String lis:list){  
  68.             maps.put(lis.split("=")[0],lis.split("=")[1]);  
  69.         }  
  70.         return maps;  
  71.     }  
  72.   
  73.     public String getUserName() {    
  74.         return userName;    
  75.     }    
  76.     
  77.     public void setUserName(String userName) {    
  78.         this.userName = userName;    
  79.     }    
  80.     
  81.     public String getPassword() {    
  82.         return password;    
  83.     }    
  84.     
  85.     public void setPassword(String password) {    
  86.         this.password = password;    
  87.     }   
  88. }  

配置strus.xml 文件

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5.   
  6. <struts>  
  7.     <package name="default" namespace="/actions" extends="struts-default">  
  8.         <!-- 登陆 action -->  
  9.         <action name="LoginCheckAction" class="com.hkrt.action.LoginCheckAction"/>  
  10.     </package>  
  11. </struts>  

现在服务器代码就写完了,没有与数据库进行交互。

以下。我们实现android 客户端登陆的代码:

页面如下:很难看...


代码实现的功能:记录用户名和密码,以get或post 方式请求服务。线程之间的数据交互,对UI进行绘制。

[java]  view plain copy
  1. package com.hkrt.activity;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.DataOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.UnsupportedEncodingException;  
  9. import java.net.HttpURLConnection;  
  10. import java.net.MalformedURLException;  
  11. import java.net.ProtocolException;  
  12. import java.net.URL;  
  13. import java.net.URLEncoder;  
  14.   
  15. import android.app.Activity;  
  16. import android.app.ProgressDialog;  
  17. import android.content.Context;  
  18. import android.content.Intent;  
  19. import android.content.SharedPreferences;  
  20. import android.content.SharedPreferences.Editor;  
  21. import android.net.ConnectivityManager;  
  22. import android.net.NetworkInfo;  
  23. import android.os.Bundle;  
  24. import android.os.Handler;  
  25. import android.os.Message;  
  26. import android.util.Log;  
  27. import android.view.View;  
  28. import android.view.View.OnClickListener;  
  29. import android.widget.CheckBox;  
  30. import android.widget.EditText;  
  31. import android.widget.ImageButton;  
  32. import android.widget.Toast;  
  33.   
  34. import com.hkrt.R;  
  35.   
  36. public class LoginUserActivity extends Activity {  
  37.    private static final String TAG_POST = "post 请求";  
  38.    private EditText userNameEdit,passwordEdit;  
  39.    private CheckBox checkPwd;//记录密码  
  40.    private ImageButton login;//登陆按钮  
  41.    private   SharedPreferences sharedPreferences ;//保存用户名和密码的文件  
  42.    private Editor editor;//编辑  
  43.    private ProgressDialog proDialog;  //进度条  
  44.    private Handler loginHandler;//信息处理机  
  45.    private String userName;  
  46.    private String password;  
  47.     @Override  
  48.     protected void onCreate(Bundle savedInstanceState) {  
  49.         super.onCreate(savedInstanceState);  
  50.         setContentView(R.layout.login_user_activity);  
  51.         initView();  
  52.         remberMe();  
  53.         login.setOnClickListener(submitListener);  
  54.         loginHandler = new Handler(){  
  55.             @Override  
  56.             public void handleMessage(Message msg) {  
  57.                 Bundle bundle = msg.getData();  
  58.                 boolean loginResult = (Boolean)bundle.get("isNetError");//只获取登陆失败  
  59.                  if(proDialog != null){    
  60.                         proDialog.dismiss();    
  61.                     }  
  62.                     boolean isNet =  isNetWorkAvailable(LoginUserActivity.this);  
  63.                     if(!isNet){  
  64.                            Toast.makeText(LoginUserActivity.this"当前网络不可用",  Toast.LENGTH_SHORT).show();   
  65.                     }  
  66.                     if(!loginResult) {    
  67.                          Toast.makeText(LoginUserActivity.this"错误的用户名或密码",  Toast.LENGTH_SHORT).show();    
  68.                     }    
  69.                 super.handleMessage(msg);  
  70.             }  
  71.               
  72.         };  
  73.           
  74.           
  75.     }  
  76.     //查测网络是否连接 需要添加连网权限 返回true 表示联网 返回false 表示没有联网  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  77.     public static boolean isNetWorkAvailable(Context context) {    
  78.          ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);    
  79.          NetworkInfo info = cm.getActiveNetworkInfo();    
  80.         return info != null && info.isConnected();    
  81.          
  82.     }   
  83.     //初始化UI组件  
  84.     private void initView(){  
  85.         userNameEdit = (EditText)this.findViewById(R.id.username_edit);  
  86.         passwordEdit = (EditText)this.findViewById(R.id.password_edit);  
  87.         checkPwd = (CheckBox)this.findViewById(R.id.checkPwd);  
  88.         login = (ImageButton)this.findViewById(R.id.login);  
  89.     }  
  90.     //记录密码  
  91.     private void remberMe(){  
  92.         sharedPreferences= getSharedPreferences("login",Context.MODE_PRIVATE);  
  93.         editor = sharedPreferences.edit();//获取编辑器    
  94.           
  95.         String userName =   sharedPreferences.getString("name","");  
  96.         String pwd =    sharedPreferences.getString("pwd","");  
  97.         userNameEdit.setText(userName);  
  98.         passwordEdit.setText(pwd);  
  99.         if(userName!=null && !userName.equals("")){  
  100.             checkPwd.setChecked(true);  
  101.         }  
  102.     }  
  103.      //登陆事件  
  104.        private OnClickListener submitListener = new OnClickListener() {    
  105.                 
  106.             public void onClick(View v) {    
  107.                 userName = userNameEdit.getText().toString();  
  108.                 password=passwordEdit.getText().toString();  
  109.                 if(checkPwd.isChecked()){  
  110.                     // 编辑配置    
  111.                     editor.putString("name",userName);    
  112.                     editor.putString("pwd",password);    
  113.                     editor.commit();//提交修改    
  114.                 }else{  
  115.                     editor.putString("name",null);    
  116.                     editor.putString("pwd"null);    
  117.                     editor.commit();//提交修改    
  118.                 }  
  119.                     proDialog = ProgressDialog.show(LoginUserActivity.this,"请稍候","正在登陆..."truetrue);   
  120.                     Thread loginThread = new Thread(new LoginFailureHandler());    
  121.                     loginThread.start();    
  122.             }    
  123.         };  
  124.           
  125.      // 验证是否登陆成功  
  126.     private class LoginFailureHandler implements Runnable{  
  127.   
  128.         @Override  
  129.         public void run() {  
  130.              boolean loginState = loginActionMethodPost(userName,password);  
  131.              if(loginState){  
  132.                      Intent intent = new Intent(LoginUserActivity.this,LoginUserSuccessActivity.class);  
  133.                      Bundle bun = new Bundle();  
  134.                      bun.putString("userName",userName);  
  135.                      bun.putString("password",password);  
  136.                      intent.putExtras(bun);  
  137.                      startActivity(intent);  
  138.                     proDialog.dismiss();    
  139.              }else{  
  140.                     Message message = new Message();  
  141.                     Bundle bundle = new Bundle();    
  142.                     bundle.putBoolean("isNetError",loginState);    
  143.                     message.setData(bundle);    
  144.                     loginHandler.sendMessage(message);    
  145.                        
  146.              }  
  147.         }  
  148.           
  149.     }  
  150.     //请求登陆 get 方式   
  151.     private boolean loginActionMethodGet(String name,String pwd){  
  152.         BufferedInputStream bufIn  = null;  
  153.         boolean login =false;  
  154.            String validateURL="http://10.0.2.2:8080/androidService/actions/LoginCheckAction?userName=" + name + "&password=" +pwd;   
  155.             try {  
  156.                 URL url = new URL(validateURL);  
  157.                 HttpURLConnection httpConn =  (HttpURLConnection)url.openConnection();  
  158.                 httpConn.setConnectTimeout(5000);    
  159.                 httpConn.setRequestMethod("GET");       
  160.                 httpConn.connect();    
  161.                 bufIn = new BufferedInputStream(httpConn.getInputStream());  
  162.                 if(httpConn.getResponseCode()==HttpURLConnection.HTTP_OK){  
  163.                     byte [] body = new byte [1];  
  164.                     bufIn.read(body);  
  165.                     String loginState  = new String(body);  
  166.                     if(loginState.equals("1")){ //返回1登陆成功 -1登陆失败  
  167.                         login =true;  
  168.                     }else{  
  169.                         login =false;  
  170.                     }  
  171.                 }  
  172.                   
  173.             } catch (MalformedURLException e) {  
  174.                 e.printStackTrace();  
  175.             } catch (IOException e) {  
  176.                 e.printStackTrace();  
  177.             }finally{  
  178.                   
  179.                 if(bufIn!=null){  
  180.                     try {  
  181.                         bufIn.close();  
  182.                     } catch (IOException e) {  
  183.                         e.printStackTrace();  
  184.                     }  
  185.                 }  
  186.             }  
  187.             return login;  
  188.     }  
  189.     // 登陆的 post 方式  
  190.     private boolean loginActionMethodPost(String name, String pwd) {  
  191.         boolean login = false;  
  192.         // Post方式请求  
  193.         String validateURL = "http://10.0.2.2:8080/androidService/actions/LoginCheckAction";  
  194.         // 请求的参数转换为byte数组  
  195.         String params;  
  196.         try {  
  197.             params = "userName=" + URLEncoder.encode(name, "UTF-8") + "&password=" + URLEncoder.encode(pwd,"UTF-8");  
  198.             byte[] postData = params.getBytes();  
  199.             // 新建一个URL对象  
  200.             URL url = new URL(validateURL);  
  201.             // 打开一个HttpURLConnection连接  
  202.             HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  203.             // 设置连接超时时间  
  204.             urlConn.setConnectTimeout(5 * 1000);  
  205.             // Post请求必须设置允许输出  
  206.             urlConn.setDoOutput(true);  
  207.             // Post请求不能使用缓存  
  208.             urlConn.setUseCaches(false);  
  209.             // 设置为Post请求  
  210.             urlConn.setRequestMethod("POST");  
  211.             urlConn.setInstanceFollowRedirects(true);  
  212.             // 配置请求Content-Type  
  213.             urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencode");  
  214.             // 开始连接  
  215.             urlConn.connect();  
  216.             // 发送请求参数  
  217.             DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());  
  218.             dos.write(postData);  
  219.             dos.flush();  
  220.             dos.close();  
  221.             // 判断请求是否成功  
  222.             if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {  
  223.                 // 获取返回的数据  
  224.                 byte[] data = readIS(urlConn.getInputStream());  
  225.                 if(data.length>0){  
  226.                     String loginState = new String(data);  
  227.                     if (loginState.equals("1")) {  
  228.                         login = true;  
  229.                     }  
  230.                     Log.i(TAG_POST, "Post请求方式成功,返回数据如下:");  
  231.                     Log.i(TAG_POST, new String(data, "UTF-8"));  
  232.                 }  
  233.             } else {  
  234.                 Log.i(TAG_POST, "Post方式请求失败");  
  235.             }  
  236.         } catch (UnsupportedEncodingException e) {  
  237.             e.printStackTrace();  
  238.         } catch (MalformedURLException e) {  
  239.             e.printStackTrace();  
  240.         } catch (ProtocolException e) {  
  241.             e.printStackTrace();  
  242.         } catch (IOException e) {  
  243.             e.printStackTrace();  
  244.         }finally{  
  245.               
  246.         }  
  247.   
  248.         return login;  
  249.     }  
  250.     //读取服务器返回的记录    
  251.     public static byte[] readIS(InputStream is) throws IOException {  
  252.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  253.         byte[] buff = new byte[1024];  
  254.         int length = 0;  
  255.         while ((length = is.read(buff)) != -1) {  
  256.             bos.write(buff, 0, length);  
  257.         }  
  258.         bos.flush();  
  259.         bos.close();  
  260.         return bos.toByteArray();  
  261.     }  
  262.   
  263. }  
注:服务器的请求路径,由127.0.01 改成10.0.2.2 

以上android 客户端登陆代码可以使用apache 公司的HttpClient.代码格式如下:

[java]  view plain copy
  1. // 使用Apache 提供的httpClient 发送get 请求  
  2.     private boolean loginActionMethodHttpGet(String name,String pwd){  
  3.         BufferedInputStream bufIn  = null;  
  4.         boolean login =false;  
  5.         String validateURL="http://10.0.2.2:8080/androidService/actions/LoginCheckAction?userName=" + name + "&password=" +pwd;   
  6.         HttpGet get = new HttpGet(validateURL);  
  7.         HttpClient httpClient = new DefaultHttpClient();  
  8.         try {  
  9.             HttpResponse httpResponse = httpClient.execute(get);  
  10.             HttpEntity entity = httpResponse.getEntity();  
  11.             if(entity!=null){  
  12.                 bufIn = new BufferedInputStream(entity.getContent());  
  13.                 byte [] body = new byte [1];  
  14.                 bufIn.read(body);  
  15.                 String loginState  = new String(body);  
  16.                 if(loginState.equals("1")){ //返回1登陆成功 -1登陆失败  
  17.                     login =true;  
  18.                 }else{  
  19.                     login =false;  
  20.                 }  
  21.             }  
  22.         } catch (ClientProtocolException e) {  
  23.             e.printStackTrace();  
  24.         } catch (IOException e) {  
  25.             e.printStackTrace();  
  26.         }  
  27.         return login;  
  28.     }  
  29.     // 使用Apache 提供的httpClient 发送 post 请求  
  30.     private boolean loginActionMethodHttpPost(String name,String pwd){  
  31.         boolean login =false;  
  32.         String validateURL = "http://10.0.2.2:8080/androidService/actions/LoginCheckAction";  
  33.         HttpPost httpPost = new HttpPost(validateURL);  
  34.         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  35.         HttpClient httpClient = new DefaultHttpClient();  
  36.         try {  
  37.             params.add(new BasicNameValuePair("userName", name));  
  38.             params.add(new BasicNameValuePair("password", pwd));  
  39.             httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));  
  40.             HttpResponse httpResponse = httpClient.execute(httpPost);  
  41.             if(httpResponse.getStatusLine().getStatusCode()==200){  
  42.                 String loginState = EntityUtils.toString(httpResponse.getEntity());  
  43.                 System.out.println("apache post:"+loginState);  
  44.                 if(loginState.equals("1")){ //返回1登陆成功 -1登陆失败  
  45.                     login =true;  
  46.                 }else{  
  47.                     login =false;  
  48.                 }  
  49.             }  
  50.         } catch (UnsupportedEncodingException e) {  
  51.             e.printStackTrace();  
  52.         } catch (ClientProtocolException e) {  
  53.             e.printStackTrace();  
  54.         } catch (IOException e) {  
  55.             e.printStackTrace();  
  56.         }  
  57.           
  58.         return login;  
  59.     }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值