Android_Servlet验证 HttpPost的简单登录程序

该程序通过提交数据给服务器,服务器通过servlet验证后,返回信息给客户端。

先上效果图吧:此登录的客户端Demo是通过下载的源码,服务器端我自己写的。




1、Android客户端的代码为:

[java]  view plain copy
  1. package com.loulijun.logindemo;  
  2.   
  3. import java.security.MessageDigest;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.NameValuePair;  
  9. import org.apache.http.client.HttpClient;  
  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.params.BasicHttpParams;  
  15. import org.apache.http.params.HttpConnectionParams;  
  16. import org.apache.http.protocol.HTTP;  
  17. import org.apache.http.util.EntityUtils;  
  18.   
  19. import android.app.Activity;  
  20. import android.app.AlertDialog;  
  21. import android.app.ProgressDialog;  
  22. import android.content.Context;  
  23. import android.content.DialogInterface;  
  24. import android.content.Intent;  
  25. import android.content.SharedPreferences;  
  26. import android.content.SharedPreferences.Editor;  
  27. import android.net.ConnectivityManager;  
  28. import android.net.NetworkInfo.State;  
  29. import android.os.Bundle;  
  30. import android.os.Handler;  
  31. import android.os.Message;  
  32. import android.provider.Settings;  
  33. import android.view.View;  
  34. import android.widget.Button;  
  35. import android.widget.CheckBox;  
  36. import android.widget.CompoundButton;  
  37. import android.widget.EditText;  
  38. import android.widget.Toast;  
  39.   
  40. public class LoginDemoActivity extends Activity {  
  41.     /** Called when the activity is first created. */  
  42.     private Button loginBtn;  
  43.     private Button registerBtn;  
  44.     private EditText inputUsername;  
  45.     private EditText inputPassword;  
  46.     private ProgressDialog mDialog;  
  47.     private String responseMsg = "";  
  48.     private static final int REQUEST_TIMEOUT = 5*1000;//设置请求超时10秒钟    
  49.     private static final int SO_TIMEOUT = 10*1000;  //设置等待数据超时时间10秒钟    
  50.     private static final int LOGIN_OK = 1;  
  51.       
  52.   
  53.     @Override  
  54.     public void onCreate(Bundle savedInstanceState) {  
  55.         super.onCreate(savedInstanceState);  
  56.         setContentView(R.layout.login);  
  57.         loginBtn = (Button)findViewById(R.id.login_btn_login);  
  58.         registerBtn = (Button)findViewById(R.id.login_btn_zhuce);  
  59.         inputUsername = (EditText)findViewById(R.id.login_edit_account);  
  60.         inputPassword = (EditText)findViewById(R.id.login_edit_pwd);  
  61.                   
  62.         //登录  
  63.         loginBtn.setOnClickListener(new Button.OnClickListener()  
  64.         {  
  65.   
  66.             @Override  
  67.             public void onClick(View arg0) {  
  68.                 mDialog = new ProgressDialog(LoginDemoActivity.this);  
  69.                 mDialog.setTitle("登陆");  
  70.                 mDialog.setMessage("正在登陆服务器,请稍后...");  
  71.                 mDialog.show();  
  72.                 Thread loginThread = new Thread(new LoginThread());  
  73.                   
  74.                 loginThread.start();  
  75.   
  76.             }  
  77.               
  78.         });  
  79.           
  80.         registerBtn.setOnClickListener(new Button.OnClickListener()  
  81.         {  
  82.   
  83.             @Override  
  84.             public void onClick(View arg0) {  
  85.                 Intent intent = new Intent();  
  86.                 intent.setClass(LoginDemoActivity.this, RegisterActivity.class);  
  87.                 startActivity(intent);  
  88.             }  
  89.               
  90.         });  
  91.     }  
  92.       
  93.       
  94.     private boolean loginServer(String username, String password)  
  95.     {  
  96.         boolean loginValidate = false;  
  97.         //使用apache HTTP客户端实现  
  98.         String urlStr = "http://10.0.2.2:8080/Login/Login";  
  99.         HttpPost request = new HttpPost(urlStr);  
  100.         //如果传递参数多的话,可以对传递的参数进行封装  
  101.         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  102.         //添加用户名和密码  
  103.         params.add(new BasicNameValuePair("username",username));  
  104.         params.add(new BasicNameValuePair("password",password));  
  105.         try  
  106.         {  
  107.             //设置请求参数项  
  108.             request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));  
  109.             HttpClient client = getHttpClient();  
  110.             //执行请求返回相应  
  111.             HttpResponse response = client.execute(request);  
  112.               
  113.             //判断是否请求成功  
  114.             if(response.getStatusLine().getStatusCode()==200)  
  115.             {  
  116.                 loginValidate = true;  
  117.                 //获得响应信息  
  118.                 responseMsg = EntityUtils.toString(response.getEntity());  
  119.             }  
  120.         }catch(Exception e)  
  121.         {  
  122.             e.printStackTrace();  
  123.         }  
  124.         return loginValidate;  
  125.     }  
  126.       
  127.      
  128.       
  129.     //初始化HttpClient,并设置超时  
  130.     public HttpClient getHttpClient()  
  131.     {  
  132.         BasicHttpParams httpParams = new BasicHttpParams();  
  133.         HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
  134.         HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
  135.         HttpClient client = new DefaultHttpClient(httpParams);  
  136.         return client;  
  137.     }  
  138.   
  139.     //Handler  
  140.     Handler handler = new Handler()  
  141.     {  
  142.         public void handleMessage(Message msg)  
  143.         {  
  144.             switch(msg.what)  
  145.             {  
  146.             case 0:  
  147.                 mDialog.cancel();  
  148.   
  149.                 Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show();  
  150.                 Intent intent = new Intent();  
  151.                 intent.setClass(LoginDemoActivity.this, MainActivity.class);  
  152.                 startActivity(intent);  
  153.                 finish();  
  154.                 break;  
  155.             case 1:  
  156.                 mDialog.cancel();  
  157.                 Toast.makeText(getApplicationContext(), "密码错误", Toast.LENGTH_SHORT).show();  
  158.                 break;  
  159.             case 2:  
  160.                 mDialog.cancel();  
  161.                 Toast.makeText(getApplicationContext(), "URL验证失败", Toast.LENGTH_SHORT).show();  
  162.                 break;  
  163.               
  164.             }  
  165.               
  166.         }  
  167.     };  
  168.       
  169.     //LoginThread线程类  
  170.     class LoginThread implements Runnable  
  171.     {  
  172.   
  173.         @Override  
  174.         public void run() {  
  175.             String username = inputUsername.getText().toString();  
  176.             String password = inputPassword.getText().toString();     
  177.             System.out.println("username="+username+":password="+password);  
  178.                   
  179.             //URL合法,但是这一步并不验证密码是否正确  
  180.             boolean loginValidate = loginServer(username, password);  
  181.             System.out.println("----------------------------bool is :"+loginValidate+"----------response:"+responseMsg);  
  182.             Message msg = handler.obtainMessage();  
  183.             if(loginValidate)  
  184.             {  
  185.                 if(responseMsg.equals("success"))  
  186.                 {  
  187.                     msg.what = 0;  
  188.                     handler.sendMessage(msg);  
  189.                 }else  
  190.                 {  
  191.                     msg.what = 1;  
  192.                     handler.sendMessage(msg);  
  193.                 }  
  194.                   
  195.             }else  
  196.             {  
  197.                 msg.what = 2;  
  198.                 handler.sendMessage(msg);  
  199.             }  
  200.         }  
  201.           
  202.     }  
  203.      
  204.       
  205. }  

2、服务器端的主要代码为:

由于只是一个测试Demo,所以该测试并没有通过数据库的查询,而是直接在程序中写上固定的用户名和密码进行匹配。

[java]  view plain copy
  1. public void doGet(HttpServletRequest request, HttpServletResponse response)  
  2.             throws ServletException, IOException  
  3.     {  
  4.         //response.setContentType("text/html");  
  5.         PrintWriter out = response.getWriter();  
  6.         request.setCharacterEncoding("utf-8");  
  7.           
  8.         String name = request.getParameter("username");  
  9.         //out.print(name);  
  10.         String pass = request.getParameter("password");  
  11.         //out.print(pass);  
  12.         if(("zlf").equals(name)&&"123456".equals(pass))  
  13.         {  
  14.             out.print("success");  
  15.         }  
  16.         else   
  17.         {  
  18.             out.print("failed");  
  19.         }  
  20.     }  
  21.   
  22.     /** 
  23.      * The doPost method of the servlet. <br> 
  24.      * 
  25.      * This method is called when a form has its tag value method equals to post. 
  26.      *  
  27.      * @param request the request send by the client to the server 
  28.      * @param response the response send by the server to the client 
  29.      * @throws ServletException if an error occurred 
  30.      * @throws IOException if an error occurred 
  31.      */  
  32.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  33.             throws ServletException, IOException  
  34.     {  
  35.         doGet(request, response);  
  36.     }  


如有需要,下载源码为:

改源码有下载的别人的源码,然后我自己没进行数据库连接,因此我改写了一下。在源码中,有一个android客户端文件夹,一个Login文件夹,一个LoginServlet文件夹。Login文件夹是我自己改写的servlet,测试可以正常运行。

http://download.csdn.net/download/zlfxy/4999994

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值