Android客户端与后台服务器的数据交互

Android客户端与服务器的数据交互

  这是今年7月份时在一家公司实训时自己做的一个小项目,仅仅是一个简单的模拟Android客户端与服务器的数据交互,中间会有串口通信,以及利用JDBC连接Mysql数据库的相关代码。其中网络通信采用的是HTTP协议,串口通信使用的是开源RXTX包实现。

  Android客户端:
  1. 登录界面:                                      
    
    
        
    
            
    
            
        
    
        
    
            
    
            
        
    
        
    
            
  2. 在开始业务逻辑之前先加上访问网络的授权:
     

  3. 登录业务代码:
    package com.zhou.android;
    
    import java.lang.ref.WeakReference;
    
    import com.zhou.android_services.ServiceRunException;
    import com.zhou.android_services.UserService;
    import com.zhou.android_services.UserServiceImpl;
    import com.zhou_client.R;
    
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.text.TextUtils;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    @SuppressLint("ShowToast")
    public class LoginActivity extends Activity {
    	private Button Login;
    	private Button Reset;
    	private EditText username;
    	private EditText password;
    	private static ProgressDialog dialog;
    	private UserService userService = new UserServiceImpl();
    
    	private static final int FLAG_LOGIN_SUCCESS = 1;
    	private static final String MSG_LOGIN_ERROR = "登录出错!";
    	private static final String MSG_LOGIN_SUCCESS = "登录成功!!";
    	public static final String MSG_LOGIN_FAILED = "用户名|密码错误!";
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.login_activity);
    		this.init();// 初始化控件
    		Login.setOnClickListener(new OnClickListener() {
    			@Override
    			public void onClick(View v) {
    				// TODO 自动生成的方法存根
    				final String LoginName = username.getText().toString().trim();
    				final String LoginPassword = password.getText().toString();
    
    				/**
    				 * 输入值验证
    				 */
    				if (TextUtils.isEmpty(username.getText())) {
    					username.setError("请输入用户名");
    					return;
    				}
    				if (TextUtils.isEmpty(password.getText())) {
    					password.setError("请输入密码");
    					return;
    				}
    
    				/*
    				 * Loading....
    				 */
    				if (dialog == null) {
    					dialog = new ProgressDialog(LoginActivity.this);
    				}
    				dialog.setTitle("请等待");
    				dialog.setMessage("登录中...");
    				dialog.setCancelable(false);
    				dialog.show();
    
    				/**
    				 * 副线程
    				 */
    				Thread thread = new Thread(new Runnable() {
    					@Override
    					public void run() {
    						try {
    							String result = userService.UserLogin(LoginName, LoginPassword);
    							if (result.equals("success")) {
    								myhandler.sendEmptyMessage(FLAG_LOGIN_SUCCESS);
    							} else {
    								Message msg = new Message();
    								Bundle data = new Bundle();
    								data.putSerializable("ErrorMsg", MSG_LOGIN_FAILED);
    								msg.setData(data);
    								myhandler.sendMessage(msg);
    							}
    
    						} catch (ServiceRunException e) {
    							e.printStackTrace();
    						} catch (Exception e) {
    							e.printStackTrace();
    							Message msg = new Message();
    							Bundle data = new Bundle();
    							data.putSerializable("ErrorMsg", MSG_LOGIN_ERROR);
    							msg.setData(data);
    							myhandler.sendMessage(msg);
    
    						}
    					}
    				});
    				thread.start();
    			}
    		});
    		Reset.setOnClickListener(new OnClickListener() {
    			@Override
    			public void onClick(View v) {
    				// TODO 自动生成的方法存根
    				username.setText("");
    				password.setText("");
    			}
    		});
    	}
    
    	private void showTip(String str) {
    		// Toast.makeText(LoginActivity.this, str, Toast.LENGTH_SHORT).show();
    		if (str.equals(MSG_LOGIN_SUCCESS)) {
    			Intent intent = new Intent(LoginActivity.this, GuideActivityList.class);
    			startActivity(intent);
    			LoginActivity.this.finish();
    		} else {
    			Toast.makeText(LoginActivity.this, str, Toast.LENGTH_SHORT).show();
    		}
    	}
    
    	public static class Myhandler extends Handler {
    		private final WeakReference mActivity;
    
    		public Myhandler(LoginActivity activity) {
    			mActivity = new WeakReference(activity);
    		}
    
    		@Override
    		public void handleMessage(Message msg) {
    			if (dialog != null) {
    				dialog.dismiss();
    			}
    
    			int flag = msg.what;
    			switch (flag) {
    			case 0:
    				String errorMsg = (String) msg.getData().getSerializable("ErrorMsg");
    				((LoginActivity) mActivity.get()).showTip(errorMsg);
    				break;
    			case FLAG_LOGIN_SUCCESS:
    				((LoginActivity) mActivity.get()).showTip(MSG_LOGIN_SUCCESS);
    				break;
    			default:
    				break;
    			}
    		}
    
    	}
    
    	private Myhandler myhandler = new Myhandler(LoginActivity.this);
    
    	private void init() {
    		Login = (Button) this.findViewById(R.id.btn_Login);
    
    		Reset = (Button) this.findViewById(R.id.btn_Reset);
    		username = (EditText) this.findViewById(R.id.Username);
    		password = (EditText) this.findViewById(R.id.Password);
    	}
    
    }
    

  4. Http工具类:
    package com.zhou.android_net;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.List;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    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.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    public class HttpUtils {
    	// static final String URL =
    	// "http://10.1.1.186:8080/MyServer_andrioid/login.do";
    	private static final String URL = "http://192.168.191.1:8080/MyServer_andrioid/login.do";
    	private static final String GETURL = "http://192.168.191.1:8080/MyServer_andrioid/main.do";
    	public static final String ENCODING = "UTF-8";
    	public static String TAG = "Server responce:";
    	public static String result = "it's a test.";
    
    	public HttpClient httpClient;
    	public HttpPost httpPost;
    	public HttpGet httpGet;
    
    	public HttpUtils() {
    		httpClient = new DefaultHttpClient();
    		httpPost = new HttpPost(URL);
    	}
    
    	public String SendPostMethod(List params) {
    		try {
    			UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(params, ENCODING);
    			httpPost.setEntity(encodedFormEntity);
    			HttpResponse httpResponse = httpClient.execute(httpPost);
    			HttpEntity entity = httpResponse.getEntity();
    
    			int resCode = httpResponse.getStatusLine().getStatusCode();
    			if (resCode == 200) {
    				result = (String) EntityUtils.toString(entity, ENCODING);
    			}
    			httpClient.getConnectionManager().shutdown();
    		} catch (UnsupportedEncodingException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    
    		return result;
    	}
    
    	public String SendGetMethod(List params) {
    		String param = URLEncodedUtils.format(params, ENCODING);
    		httpGet = new HttpGet(GETURL + "?" + param);
    		try {
    			HttpResponse httpResponse = httpClient.execute(httpGet);
    			int resCode = httpResponse.getStatusLine().getStatusCode();
    			if (resCode == 200) {
    				result = EntityUtils.toString(httpResponse.getEntity());
    			}
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		}
    
    		return result;
    	}
    }
    

  5. 对外提供的接口调用:
    package com.zhou.android_services;
    
    import java.util.LinkedList;
    import java.util.List;
    
    import org.apache.http.message.BasicNameValuePair;
    
    import com.zhou.android.LoginActivity;
    import com.zhou.android_net.HttpUtils;
    
    import android.util.Log;
    
    public class UserServiceImpl implements UserService{
    	private final static String TAG = "UserServiceImpl";
    	public String result = "";
    	
    	public String UserLogin(String LoginName, String LoginPassword) throws Exception {
    		// TODO 自动生成的方法存根
    		Log.d(TAG, LoginName);
    		Log.d(TAG, LoginPassword);
    		
    		HttpUtils httpUtils = new HttpUtils();
    		List params = new LinkedList();
    		params.add(new BasicNameValuePair("LoginName", LoginName));
    		params.add(new BasicNameValuePair("LoginPassword", LoginPassword));
    		result = httpUtils.SendPostMethod(params);
    	//	System.out.println("--->>"+result);
    		Thread.sleep(1000);
    		
    		if(result.equals("success") || result.equals("failed")){
    			return result;
    		}
    		else{
    			throw new ServiceRunException(LoginActivity.MSG_LOGIN_FAILED);
    		}
    	}
    
    }

Servlet服务器部分:
  1. 处理登录请求的servlet:
    package zhou.android.servlrt;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    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 zhou.android.mysql.MyserverSql;
    
    /**
     * Servlet implementation class Servlet_android
     * URL:http://localhost:8080/MyServer_andrioid/login.do
     */
    @WebServlet("/login.do")
    public class LoginServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	/**
    	 * @see HttpServlet#HttpServlet()
    	 */
    	public LoginServlet() {
    		super();
    		// TODO Auto-generated constructor stub
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
    	 *      response) URL传参:URL地址? + 参数名=参数值&参数名+参数值
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		System.out.println("--doPost-->");
    		request.setCharacterEncoding("UTF-8");
    		
    		MyserverSql mySql = new MyserverSql();
    		String loginName = request.getParameter("LoginName");
    		String loginPassword = request.getParameter("LoginPassword");
    
    		System.out.println(loginName);
    		System.out.println(loginPassword);
    		/**
    		 * @text/html
    		 */
    		response.setCharacterEncoding("UTF-8");
    		response.setContentType("text/html;charset=UTF-8");
    
    		PrintWriter out = null;
    		/**
    		 * @登录业务逻辑判断
    		 */
    		try {
    			out = response.getWriter();
    			int flag = 1;
    			flag = mySql.login(loginName, loginPassword);
    			if (flag==1) {
    				out.print("success");
    			} else {
    				out.print("failed");
    			}
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		} finally {
    			if (out != null) {
    				out.close();
    			}
    		}
    
    	}
    
    }
    

  2. 连接Mysql数据库工具类:
    package zhou.android.mysql;
    
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import com.mysql.jdbc.Connection;
    
    public class MyserverSql {
    	private Connection conn = null;
    	private Statement stmt = null;
    	private ResultSet rs = null;
    	/*
    	 * 简单写法:url =
    	 * "jdbc:myqsl://localhost/test(数据库名)? user=root(用户)&password=yqs2602555(密码)"
    	 * ;
    	 */
    	private static String url = null;
    	private final static String user = "root";
    	private final static String password = "5880172";
    	private String sql = null;
    
    	public int login(String loginName, String passWord) {
    		int flag = 0;
    		try {
    			Class.forName("com.mysql.jdbc.Driver"); // 加载mysq驱动
    		} catch (ClassNotFoundException e) {
    			System.out.println("驱动加载错误");
    			e.printStackTrace();// 打印出错详细信息
    		}
    
    		try {
    			url = "jdbc:mysql://localhost:3306/users?user=root&password=5880172&useSSL=false";
    			conn = (Connection) DriverManager.getConnection(url, user, password);
    		} catch (SQLException e) {
    			System.out.println("数据库链接错误");
    			e.printStackTrace();
    		}
    
    		try {
    			stmt = conn.createStatement();
    			sql = "select * from user";// dept这张表有deptno,deptname和age这三个字段
    			rs = stmt.executeQuery(sql);// 执行sql语句
    
    			while (rs.next()) {
    				String name = rs.getString("username");
    				String word = rs.getString("password");
    				if (loginName.equals(name)) {
    					if (passWord.equals(word)) {
    						flag = 1;
    						break;
    					} else {
    						flag = 0;
    					}
    				} else {
    					flag = 0;
    				}
    			}
    			rs.close();
    			stmt.close();
    		} catch (SQLException e) {
    			System.out.println("数据操作错误");
    			e.printStackTrace();
    		}
    		// 关闭数据库
    		try {
    			if (stmt != null) {
    				stmt.close();
    				stmt = null;
    			}
    			if (conn != null) {
    				conn.close();
    				conn = null;
    			}
    		} catch (Exception e) {
    			System.out.println("数据库关闭错误");
    			e.printStackTrace();
    		}
    		return flag;
    	}
    
    	public void insert(String time, String data) {
    		try {
    			Class.forName("com.mysql.jdbc.Driver"); // 加载mysq驱动
    		} catch (ClassNotFoundException e) {
    			System.out.println("驱动加载错误");
    			e.printStackTrace();// 打印出错详细信息
    		}
    
    		try {
    			url = "jdbc:mysql://localhost:3306/users?user=root&password=5880172&useSSL=false";
    			conn = (Connection) DriverManager.getConnection(url, user, password);
    		} catch (SQLException e) {
    			System.out.println("数据库链接错误");
    			e.printStackTrace();
    		}
    
    		try {
    			stmt = conn.createStatement(); // System.out.println(" test 1");
    			sql = "insert into log values ('" + time + "','" + data + "')";
    			stmt.executeUpdate(sql);// 执行sql语句
    
    		} catch (SQLException e) {
    			System.out.println("数据操作错误");
    			e.printStackTrace();
    		}
    
    		// 关闭数据库
    		try {
    			if (stmt != null) {
    				stmt.close();
    				stmt = null;
    			}
    			if (conn != null) {
    				conn.close();
    				conn = null;
    			}
    		} catch (Exception e) {
    			System.out.println("数据库关闭错误");
    			e.printStackTrace();
    		}
    	}
    
    	public String getDateTime() {
    		Date date = new Date();
    		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		String time = format.format(date);
    
    		return time;
    	}
    
    }
  3. 因为这个项目还涉及到了嵌入式平台的通信,所以采用了串口通信
    package zhou.android.comm;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Enumeration;
    import java.util.TooManyListenersException;
    
    import gnu.io.CommPortIdentifier;
    import gnu.io.PortInUseException;
    import gnu.io.SerialPort;
    import gnu.io.SerialPortEvent;
    import gnu.io.SerialPortEventListener;
    import gnu.io.UnsupportedCommOperationException;
    import zhou.android.mysql.MyserverSql;
    
    public class MyserverComm implements SerialPortEventListener {
    
    	// 检测系统中可用的通讯端口类
    	private static CommPortIdentifier portId;
    	private static Enumeration portList;
    	// 输入输出流
    	public static InputStream inputStream;
    	public static OutputStream outputStream;
    	// RS-232的串行口
    	public static SerialPort serialPort;
    	byte[] readBuffer = new byte[1024];
    	byte[] writeBuffer = new byte[50];
    	private int count = 0;
    	public static String Message = "";
    	public MyserverSql mysql;
    
    	// 初始化串口
    	@SuppressWarnings("unchecked")
    	public void init() {
    		portList = CommPortIdentifier.getPortIdentifiers();
    		while (portList.hasMoreElements()) {
    			portId = portList.nextElement();
    			if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    				if (portId.getName().equals("COM4")) {
    					try {
    						String name = "ZigbeePort" + count;
    						serialPort = (SerialPort) portId.open(name, 2000);
    						serialPort.addEventListener(new MyserverComm());
    						serialPort.notifyOnDataAvailable(true);
    						/* 设置串口通讯参数 */
    						serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
    								SerialPort.PARITY_NONE);
    						outputStream = serialPort.getOutputStream();
    						inputStream = serialPort.getInputStream();
    					} catch (PortInUseException e) {
    						e.printStackTrace();
    					} catch (TooManyListenersException e) {
    						e.printStackTrace();
    					} catch (UnsupportedCommOperationException e) {
    						e.printStackTrace();
    					} catch (IOException e) {
    						e.printStackTrace();
    					}
    				}
    			}
    		}
    	}
    
    	/**
    	 * 实现接口SerialPortEventListener中的方法 读取从串口中接收的数据
    	 */
    	public void serialEvent(SerialPortEvent event) {
    		switch (event.getEventType()) {
    		case SerialPortEvent.BI:
    		case SerialPortEvent.OE:
    		case SerialPortEvent.FE:
    		case SerialPortEvent.PE:
    		case SerialPortEvent.CD:
    		case SerialPortEvent.CTS:
    		case SerialPortEvent.DSR:
    		case SerialPortEvent.RI:
    		case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
    			break;
    		case SerialPortEvent.DATA_AVAILABLE:// 获取到串口返回信息
    			try {
    				int numBytes = 0;
    				while (inputStream.available() > 0) {
    					numBytes = inputStream.read(readBuffer);
    				}
    				String temp = new String(readBuffer, 0, numBytes);
    				Message = temp;
    				System.out.println("Comm-->>" + Message);
    
    				if (temp.length() == 4) {
    					temp = "温度:" + temp.substring(0, 2) + "湿度:" + temp.substring(2, 4);
    				}
    				mysql = new MyserverSql();
    				String time = mysql.getDateTime();
    				// System.out.println("时间-->>"+time);
    				mysql.insert(time, temp);
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    			readBuffer = null;
    			serialPort.removeEventListener();
    			serialPort.close();
    			break;
    		default:
    			break;
    		}
    	}
    
    	// 向串口发送信息方法
    	public void sendMsg(byte[] buffer) {
    		try {
    			outputStream.write(buffer);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    
    	public static byte[] HexString2Bytes(String src) {
    		if (null == src || 0 == src.length()) {
    			return null;
    		}
    		byte[] ret = new byte[src.length() / 2];
    		byte[] tmp = src.getBytes();
    		for (int i = 0; i < (tmp.length / 2); i++) {
    			ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
    		}
    		return ret;
    	}
    
    	public static byte uniteBytes(byte src0, byte src1) {
    		byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })).byteValue();
    		_b0 = (byte) (_b0 << 4);
    		byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue();
    		byte ret = (byte) (_b0 ^ _b1);
    		return ret;
    	}
    
    }




















 
   
 
  

你可能感兴趣的:(Android开发)