010_04用户登录(用户名,密码交给服务器并验证)

  该代码主要使用了get和post两种方式提交数据到服务器

  将常用的代码块封装成工具类一提高代码的重用性。

 1 package com.cskaoyan.webutils;
 2 
 3 import java.io.ByteArrayOutputStream;
 4 import java.io.InputStream;
 5 
 6 public class WebUtils {
 7 
 8     public static String gettextFromInputStream(InputStream is ,String charset){
 9         String text = null;
10     
11         if(charset==null){
12             charset="utf-8";
13         }
14         try {
15             ByteArrayOutputStream baos= new ByteArrayOutputStream();    
16             byte[] b = new byte[1024];
17             int len = 0;
18             while ((len=is.read(b))!=-1) {
19                 baos.write(b, 0, len);                            
20             }
21             baos.close();            
22             text = new String(baos.toByteArray(), charset);            
23         } catch (Exception e) {
24             e.printStackTrace();
25         }
26         return  text;
27     }
28 }

MainActivity.java

  1 package com.example.day10_04login;
  2 
  3 import java.io.InputStream;
  4 import java.io.OutputStream;
  5 import java.net.HttpURLConnection;
  6 import java.net.URL;
  7 import java.net.URLEncoder;
  8 import com.cskaoyan.webutils.WebUtils;
  9 import android.app.Activity;
 10 import android.os.Bundle;
 11 import android.os.Handler;
 12 import android.os.Message;
 13 import android.view.View;
 14 import android.widget.EditText;
 15 import android.widget.Toast;
 16 
 17 public class MainActivity extends Activity {
 18     @Override
 19     protected void onCreate(Bundle savedInstanceState) {
 20         super.onCreate(savedInstanceState);
 21         setContentView(R.layout.activity_main);
 22     }
 23 
 24     Handler hanlder = new Handler(){
 25         @Override
 26         public void handleMessage(Message msg) {
 27             super.handleMessage(msg);
 28             switch (msg.what) {
 29             case 1:
 30                 Toast.makeText(MainActivity.this, (String)msg.obj, 1).show();
 31                 break;
 32             case 2:
 33                 Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
 34                 break;
 35             default:
 36                 break;
 37             }
 38         }    
 39     };
 40     
 41     public void login(View v){    
 42         EditText et_username = (EditText) findViewById(R.id.et_uername);
 43         EditText et_password = (EditText) findViewById(R.id.et_password);
 44         
 45         final String username= et_username.getText().toString();
 46         final String password= et_password.getText().toString();    
 47 
 48         //发请求的线程
 49         Thread thread = new Thread(){    
 50             public void run() {
 51                 String path = "http://192.168.3.30:8080/LoginDemo/servlet/Login?username="
 52                         +URLEncoder.encode(username)+"&password="+password;
 53                 try {
 54                     URL url = new URL(path);
 55                     HttpURLConnection conn= (HttpURLConnection) url.openConnection();
 56                     conn.setReadTimeout(5000);
 57                     conn.setConnectTimeout(5000);    
 58                     conn.setRequestMethod("GET");
 59                     conn.connect();
 60                     
 61                     if(conn.getResponseCode()==200){
 62                         InputStream  is= conn.getInputStream();
 63                         String text = WebUtils.gettextFromInputStream(is, null);
 64                         Message msg = hanlder.obtainMessage();
 65                         msg.what=1;
 66                         msg.obj=text;
 67                         hanlder.sendMessage(msg);    
 68                     }
 69                     else {            
 70                         Message msg = hanlder.obtainMessage();
 71                         msg.what=2;
 72                         msg.obj="连接服务器失败";
 73                         hanlder.sendMessage(msg);                        
 74                     }
 75                     
 76                 } catch (Exception e) {
 77                     e.printStackTrace();
 78                 }    
 79             };
 80         };
 81         thread.start();    
 82     }
 83     
 84     public void login2(View v){    
 85         EditText et_username = (EditText) findViewById(R.id.et_uername);
 86         EditText et_password = (EditText) findViewById(R.id.et_password);
 87         
 88         final String username= et_username.getText().toString();
 89         final String password= et_password.getText().toString();
 90         
 91         //http://localhost/LoginDemo/servlet/Login
 92         //发请求的线程
 93         Thread thread = new Thread(){    
 94             public void run() {
 95                 String path = "http://192.168.3.30:8080/LoginDemo/servlet/Login";
 96                      //data = username=%E7%8E%8B%E9%81%93&password=123456
 97                 String data = "username="+URLEncoder.encode(username)+"&password="+password;
 98                 try {
 99                     URL url = new URL(path);
100                     HttpURLConnection conn= (HttpURLConnection) url.openConnection();
101                     //发送请求的三个参数
102                     conn.setReadTimeout(5000);
103                     conn.setConnectTimeout(5000);                    
104                     conn.setRequestMethod("POST");
105                     //使用post提交的时候需要设置的两参数正文发送数据的长度及类型
106                     conn.setRequestProperty("content-Length", data.length()+"");
107                     conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");                    
108                     //将data 放到request的请求正文
109                     conn.setDoOutput(true);
110                     OutputStream os = conn.getOutputStream();
111                     os.write(data.getBytes());
112                     //向服务器发送链接
113                     conn.connect();
114                     
115                     if(conn.getResponseCode()==200){
116                         InputStream  is= conn.getInputStream();
117                         String text = WebUtils.gettextFromInputStream(is, null);
118                         Message msg = hanlder.obtainMessage();
119                         msg.what=1;
120                         msg.obj=text;
121                         hanlder.sendMessage(msg);    
122                     }
123                     else {            
124                         Message msg = hanlder.obtainMessage();
125                         msg.what=2;
126                         msg.obj="连接服务器失败";
127                         hanlder.sendMessage(msg);                        
128                     }                    
129                 } catch (Exception e) {
130                     e.printStackTrace();
131                 }                
132             };
133         };
134         thread.start();    
135     }     
136 }

activity_main.java

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     tools:context="com.example.day10_04login.MainActivity"
 6     android:orientation="vertical" >
 7 
 8    
 9     <EditText
10         android:id="@+id/et_uername"
11         android:layout_width="fill_parent"
12         android:layout_height="wrap_content" 
13          />
14     <EditText
15         android:id="@+id/et_password"
16         android:layout_width="fill_parent"
17         android:layout_height="wrap_content" 
18          />
19     
20     <RelativeLayout
21          android:layout_width="fill_parent"
22          android:layout_height="wrap_content" 
23          >
24         <CheckBox 
25          android:id="@+id/cb_remeber"
26          android:layout_width="wrap_content"
27          android:layout_height="wrap_content" 
28          android:layout_alignParentLeft="true"
29         />
30         <Button
31         android:id="@+id/bt_login"      
32         android:layout_width="wrap_content"
33          android:layout_height="wrap_content"  
34          android:layout_alignParentRight="true"
35          android:onClick="login"
36                   android:text="get login"
37          
38         />
39         
40     </RelativeLayout>
41  
42        <RelativeLayout
43          android:layout_width="fill_parent"
44          android:layout_height="wrap_content" 
45          >
46         <CheckBox 
47          android:id="@+id/cb_remeber2"
48          android:layout_width="wrap_content"
49          android:layout_height="wrap_content" 
50          android:layout_alignParentLeft="true"
51         />
52         <Button
53         android:id="@+id/bt_login2"      
54         android:layout_width="wrap_content"
55          android:layout_height="wrap_content"  
56          android:layout_alignParentRight="true"
57          android:onClick="login2"
58          android:text="post login"
59         />
60         
61     </RelativeLayout>
62 
63 </LinearLayout>

使用MyEclipse创建一个web project,并将该project部署到tomcat上。其中servlet代码如下:

Login.java

 1 package com.example.login;
 2 
 3 import java.io.IOException;
 4 import javax.servlet.ServletException;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 public class Login extends HttpServlet {
10     public void doGet(HttpServletRequest request, HttpServletResponse response)
11             throws ServletException, IOException {
12         request.setCharacterEncoding("utf-8");
13         response.setContentType("text/html;charset=utf-8");
14 
15         String username = request.getParameter("username");
16         String password = request.getParameter("password");
17         
18 //           byte[] b=  username.getBytes("iso-8859-1"); 
19 //           username =  new String(b, "utf-8");
20         
21         //woodrow 123456
22         if("woodrow".equals(username)&&"123456".equals(password))
23         {
24             response.getWriter().write("登陆成功");
25         }
26         else {
27             response.getWriter().write("登陆失败");
28 
29         }
30     }
31 
32     public void doPost(HttpServletRequest request, HttpServletResponse response)
33             throws ServletException, IOException {
34         this.doGet(request, response);
35     }
36 }

效果图:

物随心转,境由心造,一切烦恼皆由心生。
原文地址:https://www.cnblogs.com/woodrow2015/p/4517147.html