跟服务器交互的登录Demo

服务器写死 账号密码,演示登录

服务器代码:

开发工具MyEclipse

public class LoginServlet extends HttpServlet {

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    
        //getParameter 方法中默认使用iso-8859-1对接收到的参数进行转码
        String username = request.getParameter("username"); 
        String password = request.getParameter("password");
        
        // 把乱码的字符串的字节打回原形,转成UTF-8
        String newUsername = new String(username.getBytes("iso-8859-1"),"UTF-8");
        String newPassword = new String(password.getBytes("iso-8859-1"),"UTF-8");
        
        System.out.println("newUsername:"+newUsername+",newPassword:"+newPassword);
        
        
        // tomcat默认使用iso-8859-1转码,但是iso-8859-1不支持中文,tomcat会查看操作系统的本地码表,本地字符集编码是gbk
        if("123".equals(newUsername) && "abc".equals(newPassword)){
            response.getOutputStream().write("login success".getBytes());
        }else{
            response.getOutputStream().write("login failture".getBytes());
        }
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request,response);
    }

}


客户端代码

开发工具:Android eclipse

public class MainActivity extends Activity {

	private EditText et_qq;
	private EditText et_pwd;
	private String path = "http://192.168.7.171:8080/web/servlet/LoginServlet";

	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			String result = (String) msg.obj;
			Toast.makeText(MainActivity.this, result, 0).show();
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		// 得到两个输入框
		et_qq = (EditText) findViewById(R.id.et_qq);
		et_pwd = (EditText) findViewById(R.id.et_pwd);
	}

	public void login(View v){
		// 以get方式向服务器端提交数据
		final String qq = et_qq.getText().toString().trim();
		final String pwd = et_pwd.getText().toString().trim();
		
		if(TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)){
			Toast.makeText(this, "qq号码和密码都不能为空", 0).show();
			return;
		}else{
			new Thread(){
				public void run() {
					try {
						
						// 1.创建一个URL对象,打开一个http类型的连接
						URL url = new URL(path);
						HttpURLConnection conn = (HttpURLConnection) url.openConnection();
						
						String data = "username="+qq+"&password="+pwd;
						// 2.给连接设置请求参数
						conn.setRequestMethod("POST"); 
						conn.setConnectTimeout(3000); // 设置连接的超时时间
						
						conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
						conn.setRequestProperty("Content-Length", data.length()+"");
						//conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
						
						
						// 以二进制流的形式写到服务器端;
						// 设置是否允许把数据写到服务器端,true表示允许,false表示不允许
						conn.setDoOutput(true);
						
						conn.getOutputStream().write(data.getBytes());
						// 3.得到服务器端返回的响应码是否为200,应该接收服务器端返回的二进制输入流
						// 得到服务器端返回的响应码
						int code = conn.getResponseCode();
						if(code == 200){
							//接收服务器端返回的二进制输入流
							InputStream is = conn.getInputStream();
							String result = StreamTools.readStream(is);
							
							Message msg = Message.obtain();
							msg.obj = result;
							handler.sendMessage(msg);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

				};
			}.start();
		}
	}

}

 StreamTool.java

public class StreamTools {

    
    /**
     * 把二进制数据转换成字符串
     * @param is
     * @return
     */
    public static String readStream(InputStream is) {

        String result = null;

        //  创建一个输出流,用于写数据
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        try {
            int len = -1;
            byte[] buffer = new byte[1024];
            
            while((len = is.read(buffer)) != -1){
                baos.write(buffer, 0, len);
            }
            
            result = baos.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}

Xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入qq号码"
        android:id="@+id/et_qq" />
    
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"
        android:id="@+id/et_pwd" />
    
    <Button 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登陆"
        android:onClick="login"
        />

</LinearLayout>

 

posted @ 2016-05-19 17:21  #蒲公英#  阅读(267)  评论(0)    收藏  举报