Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android客戶端通過json連接servlet服務端

android客戶端通過json連接servlet服務端

編輯:關於Android編程

開發一個基於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++;
 
        }

 

謝謝。

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved