android客户端通过json连接servlet服务端

开发一个基于android的app作为一个客户端,servlet作为服务端实现简单的注册与登陆功能。通过json来传递数据,进行验证和插入。由于对json的具体规范化没做过多了解,且处于学习阶段,难免会有一些错误,尽请谅解。

本文采用的工具有tomcat ,eclipse,android studio, mysql,jdk1.8;

jar包有json-simple-1.1.1.jar,mysql-connectior-java-5.1.20-bin.jar

1.先用mysql建立一个简单的数据库文件;

mysql->create databases test;->use test;->

CREATE TABLE `admin` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `UserName` varchar(20) DEFAULT NULL,
  `PassWord` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

记住数据库的字符集设置为utf8;

数据库到这里就创建完了。

2.设置服务端程序,先在eclipse中创建 Dynamic Web Project项目

(配置tomcat服务器 和jdk不写在本文中)

下图为工程文件示例:


DBConnectionHandler.java文件是用来连接数据库的文件,以下为参考代码:

package org.DBConnection;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
 
 
public class DBConnectionHandler {
 
    Connection con = null;
 
    public static Connection getConnection() {
        Connection con = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");//Mysql Connection
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DBConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
           // con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");//mysql database
        	String url="jdbc:mysql://localhost:3306/test?user=root&password=123456&characterEncoding=utf-8&useUnicode=true";
			con=DriverManager.getConnection(url);
        } catch (SQLException ex) {
            Logger.getLogger(DBConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return con;
    }
}

需要注意的是这一句:

String url="jdbc:mysql://localhost:3306/test?user=root&password=123456&characterEncoding=utf-8&useUnicode=true";

是连接Mysql的文件,其中user后面的是mysql的账号,password后面的是Mysql的密码。在后面的是传递的字符集设置为UTF-8格式,防止乱码。

LoginServlet.java文件是Servlet文件,用doget来得到客户端传进来的数据在与sql语句在数据库中进行操纵,得到一个结果,返回给客户端。

package org.servlet;

import org.DBConnection.DBConnectionHandler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.Enumeration;
import org.json.simple.JSONObject;
 
public class LoginServlet extends HttpServlet {
 
    // 
    /** 
     * Handles the HTTP GET method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
     //   response.setContentType("text/html;charset=UTF-8");
        JSONObject json = new JSONObject();
        
        //ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
        Enumeration paramNames = request.getParameterNames();
      
        String params[] = new String[2];
        int i = 0;
        while (paramNames.hasMoreElements()) {
        	 response.setContentType("text/html;charset=utf-8");
     		request.setCharacterEncoding("utf-8");
            String paramName = (String) paramNames.nextElement();
           // System.out.println(paramName);
            String[]  paramValues= request.getParameterValues(paramName);
            paramValues[0] = new String( paramValues[0].getBytes("iso-8859-1"),"UTF-8");
            params[i] = paramValues[0];
          
            //System.out.println(params[i]);
            i++;
 
        }
 
        String sql = "SELECT UserName, PassWord FROM admin where UserName=? and PassWord=?";
        Connection con = DBConnectionHandler.getConnection();
         
        try {
            PreparedStatement ps = con.prepareStatement(sql);
           
           
            ps.setString(1, params[0]);
            ps.setString(2, params[1]);
            
            ResultSet rs = ps.executeQuery();
            

            if (rs.next()) {
                json.put("info", "success");
            } else {
                json.put("info", "fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //System.out.println(json);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json.toString());
    }
 
    /** 
     * Handles the HTTP POST method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}


可以在url中测试数据。后面会提及。

RegisterServlet.java 文件内容:

package org.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.DBConnection.DBConnectionHandler;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegisterServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// response.getWriter().append("Served at:
		// ").append(request.getContextPath());
		
		JSONObject json = new JSONObject();
		// ObjectOutputStream out = new
		// ObjectOutputStream(response.getOutputStream());
		Enumeration paramNames = request.getParameterNames();
		String params[] = new String[2];
		int i = 0;
		while (paramNames.hasMoreElements()) {
			 response.setContentType("text/html;charset=utf-8");
	     		request.setCharacterEncoding("utf-8");
			String paramName = (String) paramNames.nextElement();

			String[] paramValues = request.getParameterValues(paramName);
			paramValues[0] = new String( paramValues[0].getBytes("iso-8859-1"),"UTF-8");
			params[i] = paramValues[0];

			i++;

		}
		Connection conn = DBConnectionHandler.getConnection();
		String sql = "insert into admin(UserName,PassWord) values(?,?)";
		String sql2 = "select * from admin where UserName=?";
		try {
			response.setContentType("text/html; charset=utf-8");
			PreparedStatement ps = conn.prepareStatement(sql2);
			ps.setString(1, params[0]);

			ResultSet rs = ps.executeQuery();
			if (!rs.next()) {
				PreparedStatement pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, params[0]);
				pstmt.setString(2, params[1]);
			
				
			
				int row = pstmt.executeUpdate();
				if (row >= 1)
					json.put("info", "success");
				else
					json.put("info", "fail");
			} else
				json.put("info", "fail");
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(json.toString());

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);

	}

}

Web.xml配置文件:(此文件在WebContent->Web_INF文件夹下)



	test1
	
		index.html
		index.htm
		index.jsp
		default.html
		default.htm
		default.jsp
	
	
		
		LoginServlet
		LoginServlet
		org.servlet.LoginServlet
	
	
		LoginServlet
		/login.do
	

	
		
		RegisterServlet
		RegisterServlet
		org.servlet.RegisterServlet
	
	
		RegisterServlet
		/register.do
	


这里就是服务端的所有程序,可以通过url来检测传入得到的数据是否正确.

检测LoginServlet.java程序的正确情况:

提前在Mysql数据库中admin表中插入一条数据账号为admin,密码为admin.

运行服务器后,在常用浏览器中输入http://localhost:8080/test1/login.do?u=admin&p=admin

浏览器会打印出{"info","success"}。u=后面或者p=后面输入其他的值,浏览器打印出{"info","fail"}说明用户名或者密码与之匹配的有一个错误。如果要更具体点可以在代码段修改去达到自己预期的效果。

检测RegisterServlet.java程序的正确情况:

在浏览器中输入http://localhost:8080/test1/register.do?u=测试中文&p=admin

会打印出来{“info”,"success"},在去数据库文件中查看是否有一条,用户名是测试中文,密码是admin的数据。

一般情况而言只有相同的用户名存在的情况下会打印出来{"info","fail"}的情况。这段是通过在RegisterServlet.java程序中,根据get到的UserName的值通过一条sql语句检索数据库中是否存在一条相同用户名的数据,只有不存在的情况下才进行后续的插入语句,否则会直接反馈一个失败的语句。

客户端程序:

需要提前在build.gradle配置文件

dependencies {...}
中加一句

android{ useLibrary 'org.apache.http.legacy' }

JSONParser(引用别人之前的代码参考):

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    static InputStream iStream = null;
    static JSONArray jarray = null;
    //static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      List params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
    /////////////////////////////////
    public JSONArray getJSONFromUrl(String url) {

        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e("==>", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Parse String to JSON object
        try {
            jarray = new JSONArray( builder.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON Object
        return jarray;

    }


    public JSONObject makeHttpRequest2(String url) {

        // Making HTTP request
        try {

            // check for request method
            //if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            //  httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

//            }else if(method == "GET"){
//                // request method is GET
//                DefaultHttpClient httpClient = new DefaultHttpClient();
//                //String paramString = URLEncodedUtils.format(params, "utf-8");
//                url += "?" + paramString;
//                HttpGet httpGet = new HttpGet(url);
//
//                HttpResponse httpResponse = httpClient.execute(httpGet);
//                HttpEntity httpEntity = httpResponse.getEntity();
//                is = httpEntity.getContent();
//            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}
Login界面的布局文件,
acitivity.xml文件



    
        
        
        
        
        
        

        
        
        
        

        
        

登陆的客户端代码文件:

package com.example.xyf.myapplication;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
    EditText uname, password;
    Button submit;
    // Creating JSON Parser object
    private String user;
    JSONParser jParser = new JSONParser();

    JSONObject json;
    private static String url_login = "http://192.168.191.1:8080/test1/login.do";
    //JSONArray incoming_msg = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewsById();
        submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // execute method invokes doInBackground() where we open a Http URL connection using the given Servlet URL
                //and get output response from InputStream and return it.
                new Login().execute();

            }
        });
    }
    private void findViewsById() {

        uname = (EditText) findViewById(R.id.txtUser);
        password = (EditText) findViewById(R.id.txtPass);
        submit = (Button) findViewById(R.id.button1);
    }
    private class Login extends AsyncTask{

        @Override
        protected String doInBackground(String... args) {
            // Getting username and password from user input
            String username = uname.getText().toString();
            String pass = password.getText().toString();

            List params = new ArrayList();
            params.add(new BasicNameValuePair("u",username));
            params.add(new BasicNameValuePair("p",pass));
            json = jParser.makeHttpRequest(url_login, "GET", params);
            String s=null;

            try {
                s= json.getString("info");
                Log.d("Msg", json.getString("info"));
                if(s.equals("success")){
                    user=username;
                    Intent login = new Intent(getApplicationContext(), Welcome.class);
                    login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(login);
                    finish();
                }
                else
                {

                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

    }




    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

需要注意的是:

private static String url_login = "http://192.168.191.1:8080/test1/login.do";
我是用android真机与PC构建局域网络,远程的话只需要将192.168.191.1替换掉。

注册单元代码类似,此文不写入,只需要将login.do替换成register.do

如果注册界面需要添加不止账号密码两项数据,客户端和服务端的部分代码都需要修改。

同时此文章统一的编码为utf-8.不符合这一标准会出现乱码情况,具体情况具体分析。

此文通过此代码对url传递到servlet中的数据进行处理,最后解决乱码问题:

 while (paramNames.hasMoreElements()) {
        	 response.setContentType("text/html;charset=utf-8");
     		request.setCharacterEncoding("utf-8");
            String paramName = (String) paramNames.nextElement();
           // System.out.println(paramName);
            String[]  paramValues= request.getParameterValues(paramName);
            paramValues[0] = new String( paramValues[0].getBytes("iso-8859-1"),"UTF-8");
            params[i] = paramValues[0];
          
            //System.out.println(params[i]);
            i++;
 
        }

谢谢。


你可能感兴趣的:(Android学习)