Android之使用HttpPost提交数据到服务器(Android手机客户端和后台服务器交互)

这是一个小型的数据交互案例,即Android手机客户端和后台服务器交互(数据库mysql)

服务器端

首先服务器端数据库(用户名root密码123456),db_student.sql数据库表userinfo(用户名admin,密码123)

访问数据库的工具类DBManager.java

package com.jdbc.db;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 负责访问数据库的工具类
 * @author liuya
 *
 */
public class DBManager {
	
	//数据库的用户名和密码
	private final String USERNAME="root";
	private final String PSWD="123456";
	
	//数据库驱动
	private final String DRIVER="com.mysql.jdbc.Driver";
	private final String URL="jdbc:mysql://localhost:3306/db_student";
	private Connection connection;//连接数据库
	private PreparedStatement pstmt;//采用预编译的sql语句执行添加、删除、修改和查询的功能,效率高
	private ResultSet rs;//查询返回的结果集合
	private static DBManager instance;
	
	private DBManager() {
		// TODO Auto-generated constructor stub
		
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void getConnection(){
		try {
			connection=DriverManager.getConnection(URL, USERNAME, PSWD);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 使用单例模式获得数据库的访问对象:保证数据的安全性
	 * @return
	 */
	public static DBManager getInstance(){
		if(instance==null){
			instance=new DBManager();
		}
		return instance;
	}
	
	/**
	 * 释放连接
	 */
	public void releaseConn(){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(pstmt!=null){
			try {
				pstmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(connection!=null){
			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 功能:对数据库表的增加删除和修改功能
	 * @param sql
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public boolean updateBySql(String sql,List params) throws SQLException{
		boolean flag=false;
		pstmt=connection.prepareStatement(sql);
		int index=1;
		if(params!=null&&!params.isEmpty()){
			for(int i=0;i0?true:false;
		return flag;
	}
	
	/**
	 * 使用Java的反射机制封装查询,查询返回单条记录
	 * @param sql
	 * @param params
	 * @param cls
	 * @return
	 * @throws Exception
	 */
	public T querySingleResultRef(String sql,Listparams,Class cls) throws Exception{
		T t=null;
		pstmt=connection.prepareStatement(sql);
		int index=1;
		if(params!=null&&!params.isEmpty()){
			for(int i=0;i List queryMultResultRef(String sql,List params,Classcls) throws Exception{
		List list=new ArrayList();
		pstmt=connection.prepareStatement(sql);
		int index=1;
		if(params!=null&&!params.isEmpty()){
			for(int i=0;i querySingleMap(String sql,List params) throws SQLException{
		Map map=new HashMap();
		pstmt=connection.prepareStatement(sql);
		int index = 1;
		if (params != null && !params.isEmpty()) {
			for (int i = 0; i < params.size(); i++) {
				pstmt.setObject(index++, params.get(i));
			}
		}
		rs = pstmt.executeQuery();
		ResultSetMetaData metaData = rs.getMetaData();
		int cols_len = metaData.getColumnCount();
		while (rs.next()) {
			for (int i = 0; i < cols_len; i++) {
				String key = metaData.getColumnName(i + 1);
				Object value = rs.getObject(key);
				if (value == null) {
					value = "";
				}
				map.put(key, value);
			}
		}
		return map;
	}
	
	/**
	 * 使用封装查询,查询返回一个List>表示多行记录
	 * @param sql
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public List> queryMultMap(String sql,List params) throws SQLException{
		List> list=new ArrayList>();
		pstmt=connection.prepareStatement(sql);
		int index = 1;
		if (params != null && !params.isEmpty()) {
			for (int i = 0; i < params.size(); i++) {
				pstmt.setObject(index++, params.get(i));
			}
		}
		rs = pstmt.executeQuery();
		ResultSetMetaData metaData = rs.getMetaData();
		int cols_len = metaData.getColumnCount();
		while (rs.next()) {
			Map map = new HashMap();
			for (int i = 0; i < cols_len; i++) {
				String key = metaData.getColumnName(i + 1);
				Object value = rs.getObject(key);
				if (value == null) {
					value = "";
				}
				map.put(key, value);
			}
			list.add(map);
		}
		return list;
	}
} 
  

一、开发服务器端

①创建登录LoginService.java(接口interface)

package com.android.login;

import java.util.List;

//判断用户是否存在
public interface LoginService {
	public boolean isUserExitLogin(List params);
}
②声明LoginDao.java实现 
  LoginService.java 
  

package com.android.login;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.jdbc.db.DBManager;

public class LoginDao implements LoginService {

	private DBManager manager;
	
	public LoginDao() {
		// TODO Auto-generated constructor stub
		manager=DBManager.getInstance();
	}
	
	@Override
	public boolean isUserExitLogin(List params) {
		// TODO Auto-generated method stub
		String sql="select * from userinfo where username=? and password=?";
		manager.getConnection();
		Map map=null;
		boolean flag=false;
		try {
			map=manager.querySingleMap(sql, params);
			flag=map.isEmpty()?false:true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return flag;
	}

}
③给手机客户端提供一个接口(Servlet)LoginAction 
  

package com.android.login;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 net.sf.json.JSONSerializer;

/**
 * Servlet implementation class LoginAction
 */
@WebServlet("/LoginAction")
public class LoginAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private LoginService service;
	  @Override
	    public void init() throws ServletException {
	    	// TODO Auto-generated method stub
	    	super.init();
	    	service=new LoginDao();
	    }
	  
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginAction() {
        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
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		List params=new ArrayList();
		params.add(username);
		params.add(password);
		boolean flag=service.isUserExitLogin(params);
		if(flag){
			ResultMessage message=new ResultMessage(1,"登录成功");
			Map
			map=new HashMap();
			map.put("result", message);
			String jsonString=JSONSerializer.toJSON(map).toString();
			writer.println(jsonString);
		}
		writer.flush();
		writer.close();
	}

}
④创建对象ResultMessage.java 
  

package com.android.login;

public class ResultMessage {
	private int resultCode;// 结果码
	private String resultMessage;// 结果信息

	public int getResultCode() {
		return resultCode;
	}

	public void setResultCode(int resultCode) {
		this.resultCode = resultCode;
	}

	public String getResultMessage() {
		return resultMessage;
	}

	public void setResultMessage(String resultMessage) {
		this.resultMessage = resultMessage;
	}

	public ResultMessage() {
		// TODO Auto-generated constructor stub
	}

	public ResultMessage(int resultCode, String resultMessage) {
		super();
		this.resultCode = resultCode;
		this.resultMessage = resultMessage;
	}
}
二、开发手机客户端(简单登录)

①在activity_main.xml设置界面如下,在清单文件中加网络授权:Permissions->Add->Uses Permission->ok->在右边的name中查找INTERNET

Android之使用HttpPost提交数据到服务器(Android手机客户端和后台服务器交互)_第1张图片
②在MainActivity.java中实例化控件

③创建工具类HttpUtils.java

package com.example.android_httppost_login.http;

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

import org.apache.http.HttpResponse;
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 org.apache.http.util.EntityUtils;

public class HttpUtils {

	public HttpUtils() {
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * 
	 * @param path
	 * @param params 模拟http表单数据
	 * @param encode
	 * @return
	 */
	public static String sendPostMethod(String path,Map params,String encoding){
		HttpClient httpClient=new DefaultHttpClient();
		HttpPost httpPost=new HttpPost(path);
		String result="";
		List parameters=new ArrayList();
		try {
			if(params!=null&&!params.isEmpty()){
				for(Map.Entry entry:params.entrySet()){
					String name=entry.getKey();
					//String value=URLEncoder.encode( entry.getValue().toString(),encoding);//如果出现乱码问题,则修改
					String value=entry.getValue().toString();
					BasicNameValuePair valuePair=new BasicNameValuePair(name, value);
					parameters.add(valuePair);
				}
			}
			
			UrlEncodedFormEntity encodedFormEntity=new UrlEncodedFormEntity(parameters,encoding);//纯文本表单,不包含文件
			httpPost.setEntity(encodedFormEntity);
			HttpResponse httpResponse=httpClient.execute(httpPost);
			if(httpResponse.getStatusLine().getStatusCode()==200){
				result=EntityUtils.toString(httpResponse.getEntity(), encoding);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
}
④创建ResultMessage.java状态码类

package com.example.android_httppost_login.domain;

public class ResultMessage {
	private int resultCode;// 结果码
	private String resultMessage;// 结果信息

	public int getResultCode() {
		return resultCode;
	}

	public void setResultCode(int resultCode) {
		this.resultCode = resultCode;
	}

	public String getResultMessage() {
		return resultMessage;
	}

	public void setResultMessage(String resultMessage) {
		this.resultMessage = resultMessage;
	}

	public ResultMessage() {
		// TODO Auto-generated constructor stub
	}

	public ResultMessage(int resultCode, String resultMessage) {
		super();
		this.resultCode = resultCode;
		this.resultMessage = resultMessage;
	}
}
⑤创建json字符串解析工具类JsonTools.java

package com.example.android_httppost_login.json;

import org.json.JSONObject;

import com.example.android_httppost_login.domain.ResultMessage;

public class JsonTools {
	
	public JsonTools() {
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * {"result":{"resultCode":1,"resultMessage":"登录成功"}} 
	 * @param jsonString
	 * @return
	 */
	public static ResultMessage getResultMessage(String jsonString){
		ResultMessage message=null;
		
		try {
			JSONObject sourceObject=new JSONObject(jsonString);
			JSONObject jsonObject=sourceObject.getJSONObject("result");
			message=new ResultMessage();
			message.setResultCode(jsonObject.getInt("resultCode"));
			message.setResultMessage(jsonObject.getString("resultMessage"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return message;
	}
}

⑥在MainActivity.java处理(用异步任务处理post请求)

package com.example.android_httppost_login;

import java.util.HashMap;
import java.util.Map;

import com.example.android_httppost_login.domain.ResultMessage;
import com.example.android_httppost_login.http.HttpUtils;
import com.example.android_httppost_login.json.JsonTools;

import android.support.v7.app.ActionBarActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
	
	private Button btn;
	private EditText usernameEdt;
	private EditText passwordEdt;
	private ProgressDialog dialog;
	private final String LOGIN_PATH="http://192.168.1.100:8080/Httppost_Web/LoginAction";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn=(Button) this.findViewById(R.id.button1);
		usernameEdt=(EditText) this.findViewById(R.id.editText1);
		passwordEdt=(EditText) this.findViewById(R.id.editText2);
		dialog=new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("正在登录,请稍候...");
		btn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String name_value=usernameEdt.getText().toString().trim();
				String pswd_value=passwordEdt.getText().toString().trim();
				Map params=new HashMap();
				params.put("url", LOGIN_PATH);
				params.put("username", name_value);
				params.put("password", pswd_value);
				try {
					String result=new LoginAsyncTask().execute(params).get();
					ResultMessage message=JsonTools.getResultMessage(result);
					if(message.getResultCode()==1){
						Toast.makeText(MainActivity.this, message.getResultMessage(), 1).show();
						Intent intent=new Intent(MainActivity.this,NextActivity.class);
						startActivity(intent);
					}
					
					System.out.println("--->>"+result);
				} catch (Exception e) {
					// TODO: handle exception
				}
				
			}
		});
	}
	
	class LoginAsyncTask extends AsyncTask, Void, String>{

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog.show();
		}
		
		@Override
		protected String doInBackground(Map... params) {
			// TODO Auto-generated method stub
			Map map=params[0];
			//表单数据
			Map params2=new HashMap();
			params2.put("username", map.get("username"));
			params2.put("password", map.get("password"));
			String result=HttpUtils.sendPostMethod(map.get("url"), params2, "utf-8");
			return result;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
		}
		
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@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);
	}
}


你可能感兴趣的:(Android)