Android客户端与Tomcat服务器通信实现登录验证

  • Post author:
  • Post category:其他


一.功能描述




Android

客户端实现登录界面,当将用户名和密码填入文本框并点击登录按钮时,将认证信息传送至


Tomcat


服务器进行认证,若用户名和密码匹配,则


Android


客户端提示登录成功,否则提示登陆失败。

二.开发环境

Android

客户端:


Android Studio2.2.3


服务器端:

MyEclipse2016 + Tomcat9.0

三.详细过程

(1)Android

客户端的开发


新建一个名为

LoginGuest

的工程,该工程只包含


LoginActivity





LoginToServer


两个类,其中LoginToServer对象在LoginActivity中被调用,实现向服务器的信息传递。在


AndroidManifest.xml


中添加网络权限:





实现

LoginActivity

的布局文件


activity_login.xml


的布局:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_login"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.leidong.guesttest.LoginActivity"
    android:orientation="vertical">
    <TextView
        android:text="登录界面"
        android:textSize="40dp"
        android:textColor="#003399"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1"
        android:gravity="center_horizontal"
        android:layout_margin="10dp"/>

    <TextView
        android:text="用户名~~~~~~~~~~~~~~~~~~~"
        android:textSize="20dp"
        android:textColor="#CC0000"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        android:layout_margin="10dp"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/et_username"
        android:textSize="20dp"
        android:textColor="#003399"
        android:layout_margin="10dp"/>

    <TextView
        android:text="密码   ~~~~~~~~~~~~~~~~~~~~"
        android:textSize="20dp"
        android:textColor="#CC0000"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView3"
        android:layout_margin="10dp"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/et_password"
        android:textSize="20dp"
        android:textColor="#003399"
        android:layout_margin="10dp"/>

    <Button
        android:text="登录"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bt_login"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="#0099FF"/>
</LinearLayout>


效果如下:



写GuestToServer类

package com.example.leidong.loginguest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by leido on 2017/2/15.
 */

public class GuestToServer {
    //由于Tomcat服务器部署在本地,url为本地Tomcat服务的url,IP地址为本地主机IP地址
    private String url = "http://XXX.XXX.XXX.XXX:8080/LoginServer/LoginServlet";
    //服务器返回的结果
    String result = "";

    /**
     * 使用Post方式向服务器发送请求并返回响应
     * @param username 传递给服务器的username
     * @param password 传递给服务器的password
     * @return
     */
    public String doPost(String username, String password) throws IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        //将username与password参数装入List中
        NameValuePair param1 = new BasicNameValuePair("username", username);
        NameValuePair param2 = new BasicNameValuePair("password", password);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(param1);
        params.add(param2);
        //将参数包装如HttpEntity中并放入HttpPost的请求体中
        HttpEntity httpEntity = new UrlEncodedFormEntity(params, "GBK");
        httpPost.setEntity(httpEntity);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        //如果响应成功
        if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            //得到信息体
            HttpEntity entity = httpResponse.getEntity();
            InputStream inputStream = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String readLine = null;
            while((readLine = br.readLine()) != null){
                result += readLine;
            }
            inputStream.close();
            return result;
        }
        //响应失败
        else{
            return "Error";
        }
    }
}

注意Android6.0之后SDK不支持HttpClient,此时需要在build.gradle中的android{……}中

加入如下代码:

写LoginActivity类

package com.example.leidong.loginguest;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;

public class LoginActivity extends AppCompatActivity {
    //登录用户名输入框
    private EditText et_username;
    //登录密码输入框
    private EditText et_password;
    //登录按钮
    private Button bt_login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //获取组件
        init();

        //对登录按钮的点击监控
        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Handler myHandler = new Handler(){
                    public void handleMessage(Message msg){
                        String responseResult = (String)msg.obj;
                        //登录成功
                        if(responseResult.equals("true")){
                            Toast.makeText(LoginActivity.this, "登录成功!", Toast.LENGTH_LONG).show();
                        }
                        //登录失败
                        else{
                            Toast.makeText(LoginActivity.this, "登录失败!", Toast.LENGTH_LONG).show();
                        }
                    }
                };

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        GuestToServer guestToServer = new GuestToServer();
                        try {
                            String result = guestToServer.doPost(et_username.getText().toString().trim(), et_password.getText().toString().trim());
                            Message msg = new Message();
                            msg.obj = result;
                            myHandler.sendMessage(msg);

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

    }

    /**
     * 获取组件
     */
    private void init() {
        et_username = (EditText)findViewById(R.id.et_username);
        et_password = (EditText)findViewById(R.id.et_password);
        bt_login = (Button)findViewById(R.id.bt_login);
    }
}

(2)MyEclipse、Tomcat服务器端的开发


新建一个Java Web工程,新建一个名为LoginServlet的Servlet, 修改器deGet()方法,,代码如下:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if("hahaha".equals(username) && "123456".equals(password)){
		    out.print(true);
		}
		else{
			out.print(false);
		}
	}


默认的正确用户名为hahaha,正确密码为123456



此时打开服务器在后台看到其已经运行


四.运行结果

(1)输入错误的用户名或密码


(2)输入正确的用户名和密码



版权声明:本文为ldld1717原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。