`
hanwei59
  • 浏览: 34541 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
JDBC工具类1
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONObject;

/**
 * 数据库操作工具类
 * 
 * @author hanwei wei.han@neusoft.com
 * @version $Revision$
 */
public class DatabaseUtil {
	
	private Connection connection;
	
	/**
	 * 获取JDBC连接
	 * @return
	 * @throws SQLException
	 * @author hanwei
	 * @update 2011-6-8 
	 */
	public static Connection getConnection() throws SQLException {
		return C3P0ConnectionPool.getConnection();
	}
	
	/**
	 * 查询数据库,返回List结果集
	 * @param sql
	 * @param para
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-17
	 */
	public static List queryForList(String sql, Object[] para) throws Exception{
		List list = new ArrayList();
		Connection conn = getConnection();
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			if(para!=null){
				for(int i=0,l=para.length;i<l;i++){
					ps.setObject(i+1, para[i]);
				}
			}
			ResultSet rs = ps.executeQuery();
			ResultSetMetaData metaData = rs.getMetaData();
			while(rs.next()){
				Map map = new HashMap();
				for (int i = 0; i < metaData.getColumnCount(); i++) {
					String columnLabel = metaData.getColumnLabel(i+1);
					switch (metaData.getColumnType(i+1)) {
					case Types.VARCHAR:
						map.put(columnLabel, rs.getString(columnLabel));
						break;
					case Types.DATE:
						Date date = rs.getDate(columnLabel);
						if(date == null){
							map.put(columnLabel, null);
							break;
						}
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						map.put(columnLabel, sdf.format(date));
						//map.put(columnLabel, Long.valueOf(date.getTime()));
						break;
					default:
						map.put(columnLabel, rs.getObject(columnLabel));
						break;
					}
				}
				list.add(map);
			}
			rs.close();
			ps.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		} finally{
			if(conn != null && !conn.isClosed()){
				conn.close();
			}
		}
		return list;
	}
	
	/**
	 * 查询数据库,返回List结果集
	 * @param sql
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-17
	 */
	public static List queryForList(String sql) throws Exception{
		return queryForList(sql,null);
	}
	
	
	/**
	 * 查询一条记录,返回值为Map
	 * @param sql
	 * @param para
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-9
	 */
	public static Map queryForMap(String sql, Object[] para) throws Exception{
		Map map = null;
		List list = queryForList(sql,para);
		if(list!=null && list.size()>0){
			map = (Map) list.get(0);
		}
		return map;
	}
	
	
	/**
	 * 查询数据库,返回List
	 * @param sql
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-7
	 */
	public List executeQuery(String sql) throws Exception{
		return executeQuery(sql,null);
	}
	
	/**
	 * 查询数据库,返回List
	 * @param sql
	 * @param para
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-7 
	 */
	public List executeQuery(String sql, Object[] para) throws Exception{
		boolean needCloseConnection = false;//是否在本方法内完成事务,默认否
		List list = new ArrayList();
		if(connection == null || connection.isClosed()){
			connection = null;
			connection = getConnection();
			connection.setAutoCommit(true);
			needCloseConnection = true;
		}
		try {
			PreparedStatement ps = connection.prepareStatement(sql);
			if(para!=null){
				for(int i=0,l=para.length;i<l;i++){
					ps.setObject(i+1, para[i]);
				}
			}
			ResultSet rs = ps.executeQuery();
			ResultSetMetaData metaData = rs.getMetaData();
			while(rs.next()){
				Map map = new HashMap();
				for (int i = 0; i < metaData.getColumnCount(); i++) {
					String columnLabel = metaData.getColumnLabel(i+1);
					switch (metaData.getColumnType(i+1)) {
					case Types.VARCHAR:
						map.put(columnLabel, rs.getString(columnLabel));
						break;
					case Types.DATE:
						Date date = rs.getDate(columnLabel);
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						map.put(columnLabel, sdf.format(date));
						//map.put(columnLabel, Long.valueOf(date.getTime()));
						break;
					default:
						map.put(columnLabel, rs.getObject(columnLabel));
						break;
					}
				}
				list.add(map);
			}
			if(needCloseConnection){
				rs.close();
				ps.close();
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		} finally{
			if(needCloseConnection && connection != null && !connection.isClosed()){
				connection.close();
			}
		}
		return list;
	}
	
	public static String getPermaryKey(){
		UUID id = UUID.randomUUID();
		return id.toString();
	}
	/**
	 * 开始事务
	 * @throws SQLException
	 * @author hanwei
	 * @update 2011-6-9
	 */
	public void beginTransaction() throws SQLException{
		connection = getConnection();
		connection.setAutoCommit(false);
		//试解决:事务(进程 ID 367)与另一个进程被死锁在 锁 资源上,并且已被选作死锁牺牲品。请重新运行该事务。
		//connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
		//System.out.println("开始事务");
	}
	
	/**
	 * 提交事务,关闭事务
	 * @throws SQLException
	 * @author hanwei
	 * @update 2011-6-9
	 */
	public void endTransaction() throws SQLException{
		if(connection != null && !connection.isClosed()){
			connection.commit();
			connection.close();
			//System.out.println("提交事务,关闭事务");
		}
	}
	
	/**
	 * 回滚事务
	 * @throws SQLException
	 * @author hanwei
	 * @update 2011-6-16
	 */
	public void rollbackTransaction(){
		try {
			if(connection != null && !connection.isClosed()){
				connection.rollback();
				//System.out.println("提交事务,关闭事务");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 执行更新SQL
	 * @param sql
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-9
	 */
	public int executeUpdate(String sql) throws Exception{
		return executeUpdate(sql,null);
	}
	
	/**
	 * 更新数据,sql为insert或update
	 * @param sql
	 * @param para
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-8 
	 */
	public int executeUpdate(String sql, Object[] para) throws Exception{
		int retrunInt = 0;
		boolean doTransaction = false;//是否在本方法内完成事务,默认否
		if(connection == null || connection.isClosed()){
			connection = null;
			connection = getConnection();
			connection.setAutoCommit(false);
			doTransaction = true;
		}
		try {
			PreparedStatement ps = connection.prepareStatement(sql);
			if(para!=null){
				for(int i=0,l=para.length;i<l;i++){
					if(para[i] instanceof Date){
						long time = ((Date)para[i]).getTime();
						ps.setTimestamp(i+1, new java.sql.Timestamp(time));
					}else{
						ps.setObject(i+1, para[i]);
					}
				}
			}
			retrunInt = ps.executeUpdate();
			if(doTransaction){
				connection.commit();
			}
			if(doTransaction){
				ps.close();
				connection.close();
			}
		} catch (SQLException e) {
			if(connection!=null && !connection.isClosed()){
				connection.rollback();
			}
			e.printStackTrace();
			throw e;
		} finally{
			if(doTransaction && connection!=null && !connection.isClosed()){
				connection.close();//并不是真正的关闭,而是还回连接池
			}
		}
		return retrunInt;
	}
	
	/**
	 * 批量更新数据,List的元素为Object[]
	 * @param sql
	 * @param list
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-8 
	 */
	public int[] executeUpdateBatch(String sql, List list) throws Exception{
		int[] retrunInt;
		boolean doTransaction = false;//是否在本方法内完成事务,默认否
		if(connection == null || connection.isClosed()){
			connection = null;
			connection = getConnection();
			connection.setAutoCommit(false);
			doTransaction = true;
		}
		try {
			PreparedStatement ps = connection.prepareStatement(sql);
			for (int index = 0; index < list.size(); index++) {
				Object[] para = (Object[]) list.get(index);
				if(para!=null)
				for(int i=0,l=para.length;i<l;i++){
					if(para[i] instanceof Date){
						long time = ((Date)para[i]).getTime();
						ps.setTimestamp(i+1, new java.sql.Timestamp(time));
					}else{
						ps.setObject(i+1, para[i]);
					}
				}
				ps.addBatch();
			}
			retrunInt = ps.executeBatch();
			if(doTransaction){
				connection.commit();
			}
			ps.close();
			if(doTransaction){
				connection.close();
			}
		} catch (SQLException e) {
			if(connection!=null && !connection.isClosed()){
				connection.rollback();
			}
			e.printStackTrace();
			throw e;
		} finally{
			if(doTransaction && connection!=null && !connection.isClosed()){
				connection.close();//并不是真正的关闭,而是还回连接池
			}
		}
		return retrunInt;
	}
	
	/**
	 * 调用存储过程
	 * @param procedure
	 * @param param
	 * @param outNum
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-8 
	 */
	public static List callProcedure(String procedure, List param, int outNum)
    throws Exception{
        StringBuffer callBuf = new StringBuffer();
        callBuf.append("{call ");
        callBuf.append(procedure);
        callBuf.append("(");
        if (param != null){
            for (int i = 0; i < param.size(); i++){
                if (i == (param.size() - 1))
                    callBuf.append("?");
                else
                    callBuf.append("?,");
            }
        }
        callBuf.append(")}");
        String sql = callBuf.toString();
        
        Connection conn = getConnection();
        CallableStatement cs = conn.prepareCall(sql);
        if (param != null){
            for (int i = 0; i < param.size(); i++){
                Object arg = param.get(i);
                if (arg instanceof Integer)
                    cs.setInt(i + 1, Integer.parseInt(arg.toString()));
                else if (arg instanceof String)
                	cs.setString(i + 1, arg.toString());
                else if (arg instanceof Float)
                    cs.setFloat(i + 1, Float.parseFloat(arg.toString()));
                else if (arg instanceof Date){
                	Date date = (Date)arg;
                	cs.setTimestamp(i+1, new java.sql.Timestamp(date.getTime()));
                }else
                    cs.setObject(i + 1, arg.toString());
            }
        }
        
        for (int i = param.size()-outNum; i < param.size(); i++){
        	cs.registerOutParameter(i+1, Types.VARCHAR);
        }
        cs.execute();
        List list = new ArrayList(outNum);
        for (int j = param.size() - outNum; j < param.size(); j++){
            list.add(cs.getObject(j+1));
        }
        return list;
    }
	
	public static void main(String[] args) throws Exception{
		
		//插入示例、修改示例、事务示例
		/*Object[] para = new Object[10];
		para[0] = DatabaseUtil.getPermaryKey();
		para[1] = "测试患者";
		para[2] = "身份证号";
		para[3] = "男";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
		para[4] = sdf.format(new Date());
		para[5] = "矿工";
		para[6] = "地球村";
		para[7] = "021";
		para[8] = "139";
		para[9] = "DOCTOR_ID";
		DatabaseUtil dbUtil = new DatabaseUtil();
		try {
			dbUtil.beginTransaction();
			int insertInt = dbUtil.executeUpdateXmlSql("hyper_card_add", para);
			int updateInt = dbUtil.executeUpdateXmlSql("hyper_card_update"
					,new Object[]{"6666665","13888888885",para[0]});
			dbUtil.endTransaction();
		} catch (Exception e) {
			dbUtil.rollbackTransaction();
			e.printStackTrace();
		}*/
		
		//插入Map示例
		/*Map map = new HashMap();
		map.put("card_id", DatabaseUtil.getPermaryKey());
		map.put("NAME", "姓名1");
		map.put("sfzh", "身份证号");
		map.put("gender", "男");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
		map.put("birthdate", sdf.format(new Date()));
		map.put("profession", "矿工");
		map.put("address", "地球村");
		map.put("phone", "021");
		map.put("cell_phone", "139");
		map.put("doctor_id", "DOCTOR_ID");
		DatabaseUtil dbUtil = new DatabaseUtil();
		try {
			int insertInt = dbUtil.executeUpdateXmlSql("hyper_card_add", map);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		
		JSONObject json = new JSONObject();
		json.put("VISIT_ID", DatabaseUtil.getPermaryKey());
		json.put("CARD_ID", "1");
		Map map = (Map) json.toBean(json, Map.class);
		map.put("VISIT_DATE", new Date());
		Object visit_date = map.get("VISIT_DATE");
		/*Map map = new HashMap();
		map.put("VISIT_ID", DatabaseUtil.getPermaryKey());
		map.put("CARD_ID", "1");
		map.put("VISIT_DATE", new Date());*/
		DatabaseUtil dbUtil = new DatabaseUtil();
		try {
			int insertInt = dbUtil.executeUpdateXmlSql("hyper_visit_add", map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//分页查询示例
		/*String sql = new SqlXml("hyper_card_query").getSqlPage(10, 1);
//		System.out.println(sql);
		JSONArray array = JSONArray.fromObject(
				DatabaseUtil.queryForList(sql,new Object[]{"%2011%"}));
		System.out.println(array.toString());*/
		
		
		/*Map parameterMap = new HashMap();
		parameterMap.put("CARD_NO", "20110614");
//		parameterMap.put("CARD_NO", "%"+parameterMap.get("CARD_NO")+"%");
		JSONArray array = JSONArray.fromObject(
				DatabaseUtil.queryForListXmlSql("hyper_card_query", parameterMap));
		System.out.println(array.toString());*/
		
		
	}

}
读取XML配置文件(有更改时自动重新读取)
package com.neusoft.android.common.upgrade;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ServerVersionConfig {
	
	public final static String CONFIG_XML_PATH = "/upgrade.xml";

	public final static String TAG_VERSION_NORMEL = "version_code";
	public final static String TAG_VERSION_NAME = "version_name";
	public final static String TAG_VERSION_MAIN = "version_main";
	public final static String TAG_CHANGE_LOG = "change_log";
	public final static String TAG_APP_PATH = "app_path";
	
	private static ServerVersionConfig instance = null;
	private static long xmlLastModified;
	
	public int version_code;
	public String version_name;
	public int version_main;
	public String change_log;
	public String app_path;
	
	public static ServerVersionConfig getInstance(String XmlRealpath){
		File file = new File(XmlRealpath);
		if(instance == null || xmlLastModified != file.lastModified()){
			xmlLastModified = file.lastModified();
			instance = new ServerVersionConfig(XmlRealpath);
//			System.out.println("新建实例ServerVersionConfig");
		}
		return instance;
	}
	
	private ServerVersionConfig(){}
	
	private ServerVersionConfig(String XmlRealpath){
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(XmlRealpath);
			Element element = document.getDocumentElement();
			
			version_code = Integer.parseInt(getElementValueByTag(element,TAG_VERSION_NORMEL));
			version_name = getElementValueByTag(element,TAG_VERSION_NAME);
			version_main = Integer.parseInt(getElementValueByTag(element,TAG_VERSION_MAIN));
			change_log = getElementValueByTag(element,TAG_CHANGE_LOG);
			app_path = getElementValueByTag(element,TAG_APP_PATH);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String getElementValueByTag(Element element,String TagName) 
		throws DOMException {
		NodeList sqlList = element.getElementsByTagName(TagName);
		if(sqlList == null || sqlList.getLength()==0){
			return null;
		}
		Element sqlElement = (Element) sqlList.item(0);
		if(sqlElement == null){
			return null;
		}
		if(sqlElement.getFirstChild() == null){
			return null;
		}
		return sqlElement.getFirstChild().getNodeValue().trim();
	}
	
	public static void main(String[] args) throws Exception{
		ServerVersionConfig config = new ServerVersionConfig("WebRoot/upgrade.xml");
		System.out.println(config.change_log);
		System.out.println(config.app_path);
	}
}
JDBC工具类
package com.neusoft.android.common.database;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.neusoft.android.common.sql.SqlXml;

/**
 * 数据库操作工具类
 * 
 * @author hanwei wei.han@neusoft.com
 * @version $Revision$
 */
public class DatabaseUtil {
	
	private Connection connection;
	
	private String database;//目标数据库
	
	/**
	 * [构造器方法描述]
	 * @coustructor 方法.
	 */
	public DatabaseUtil(String database) {
		super();
		this.database = database;
	}
	
	/**
	 * [构造器方法描述]
	 * @coustructor 方法.
	 */
	public DatabaseUtil() {
		super();
		this.database = DBConstant.DEFAULT_DATABASE_CONNECTION;//目标数据库为空时,使用默认数据库
		//this(null);
	}

	/**
	 * 获取JDBC连接
	 * @return
	 * @throws SQLException
	 * @author hanwei
	 * @update 2011-6-8 
	 */
	public static Connection getConnection() throws SQLException {
		return C3P0ConnectionPool.getConnection();
	}
	
	/**
	 * 获取JDBC连接
	 * @param database
	 * @return
	 * @throws SQLException
	 * @author hanwei
	 * @update 2011-7-5
	 */
	public static Connection getConnection(String database) throws SQLException {
		return C3P0ConnectionPool.getConnection(database);
	}
	
	/**
	 * [方法功能中文描述]
	 * @param sql
	 * @param para
	 * @param database
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-7-5
	 */
	public static List queryForList(String sql, Object[] para, String database) throws Exception{
		List list = new ArrayList();
		Connection conn = getConnection(database);
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			if(para!=null){
				for(int i=0,l=para.length;i<l;i++){
					ps.setObject(i+1, para[i]);
				}
			}
			ResultSet rs = ps.executeQuery();
			ResultSetMetaData metaData = rs.getMetaData();
			while(rs.next()){
				Map map = new HashMap();
				for (int i = 0; i < metaData.getColumnCount(); i++) {
					String columnLabel = metaData.getColumnLabel(i+1);
					if(rs.getObject(columnLabel) == null){
						map.put(columnLabel, "");
						continue;
					}
					switch (metaData.getColumnType(i+1)) {
					case Types.VARCHAR:
						map.put(columnLabel, rs.getString(columnLabel));
						break;
					case Types.DATE:
						Date date = rs.getDate(columnLabel);
						if(date == null){
							map.put(columnLabel, null);
							break;
						}
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						map.put(columnLabel, sdf.format(date));
						//map.put(columnLabel, Long.valueOf(date.getTime()));
						break;
					default:
						map.put(columnLabel, rs.getObject(columnLabel));
						break;
					}
				}
				list.add(map);
			}
			rs.close();
			ps.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		} finally{
			if(conn != null && !conn.isClosed()){
				conn.close();
			}
		}
		return list;
	}
	
	/**
	 * 查询数据库,返回List结果集
	 * @param sql
	 * @param para
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-17
	 */
	public static List queryForList(String sql, Object[] para) throws Exception{
		return queryForList(sql,para,null);
	}
	
	/**
	 * 查询数据库,返回List结果集
	 * @param sql
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-17
	 */
	public static List queryForList(String sql) throws Exception{
		return queryForList(sql,null);
	}
	
	/**
	 * 通过配置SQL的XML查询数据库,返回List结果集
	 * @param xmlName
	 * @param para
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-17
	 */
	public static List queryForListXmlSql(String xmlName, Object[] para) throws Exception{
		SqlXml xml = new SqlXml(xmlName);
		String sql = xml.getSql();
		String db = xml.getDatabase();
		if(db != null){
			return queryForList(sql,para,db);
		}
		return queryForList(sql,para);
	}
	
	/**
	 * 通过配置SQL的XML查询数据库,返回List结果集,传入值Map的key必须与XML中的参数code一致
	 * @param xmlName
	 * @param parameterMap
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-17
	 */
	public static List queryForListXmlSql(String xmlName, Map parameterMap) throws Exception{
		SqlXml sqlxml = new SqlXml(xmlName);
		String sql = sqlxml.getSql();
		SqlXml.Param[] params = sqlxml.getParameters();
		Object[] para = new Object[params.length];
		for (int i = 0; i < params.length; i++) {
			para[params[i].order-1] = parameterMap.get(params[i].code);
			System.out.println(parameterMap.get(params[i].code));
		}
		String db = sqlxml.getDatabase();
		if(db != null){
			return queryForList(sql,para,db);
		}
		return queryForList(sql,para);
	}
	
	/**
	 * 通过配置SQL的XML查询数据库,返回List结果集
	 * @param xmlName
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-17
	 */
	public static List queryForListXmlSql(String xmlName) throws Exception{
		SqlXml xml = new SqlXml(xmlName);
		String sql = xml.getSql();
		String db = xml.getDatabase();
		if(db != null){
			return queryForList(sql,null,db);
		}
		return queryForList(sql,null);
	}
	
	/**
	 * 查询一条记录,返回值为Map
	 * @param sql
	 * @param para
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-9
	 */
	public static Map queryForMap(String sql, Object[] para) throws Exception{
		Map map = null;
		List list = queryForList(sql,para);
		if(list!=null && list.size()>0){
			map = (Map) list.get(0);
		}
		return map;
	}
	
	/**
	 * 通过配置SQL的XML查询一条记录,返回值为Map
	 * @param xmlName
	 * @param para
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-9
	 */
	public static Map queryForMapXmlSql(String xmlName, Object[] para) throws Exception{
		SqlXml xml = new SqlXml(xmlName);
		String sql = xml.getSql();
		String db = xml.getDatabase();
		if(db != null){
			List list = queryForList(sql,para,db);
			Map map = null;
			if(list!=null && list.size()>0){
				map = (Map) list.get(0);
			}
			return map;
		}
		return queryForMap(sql,para);
	}
	
	/**
	 * 查询数据库,返回List
	 * @param sql
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-7
	 */
	public List executeQuery(String sql) throws Exception{
		return executeQuery(sql,null);
	}
	
	/**
	 * 查询数据库,返回List
	 * @param sql
	 * @param para
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-7 
	 */
	public List executeQuery(String sql, Object[] para) throws Exception{
		boolean needCloseConnection = false;//是否在本方法内完成事务,默认否
		List list = new ArrayList();
		if(connection == null || connection.isClosed()){
			connection = null;
			connection = getConnection(database);
			connection.setAutoCommit(true);
			needCloseConnection = true;
		}
		try {
			PreparedStatement ps = connection.prepareStatement(sql);
			if(para!=null){
				for(int i=0,l=para.length;i<l;i++){
					ps.setObject(i+1, para[i]);
				}
			}
			ResultSet rs = ps.executeQuery();
			ResultSetMetaData metaData = rs.getMetaData();
			while(rs.next()){
				Map map = new HashMap();
				for (int i = 0; i < metaData.getColumnCount(); i++) {
					String columnLabel = metaData.getColumnLabel(i+1);
					if(rs.getObject(columnLabel) == null){
						map.put(columnLabel, "");
						continue;
					}
					switch (metaData.getColumnType(i+1)) {
					case Types.VARCHAR:
						map.put(columnLabel, rs.getString(columnLabel));
						break;
					case Types.DATE:
						Date date = rs.getDate(columnLabel);
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						map.put(columnLabel, sdf.format(date));
						//map.put(columnLabel, Long.valueOf(date.getTime()));
						break;
					default:
						map.put(columnLabel, rs.getObject(columnLabel));
						break;
					}
				}
				list.add(map);
			}
			if(needCloseConnection){
				rs.close();
				ps.close();
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		} finally{
			if(needCloseConnection && connection != null && !connection.isClosed()){
				connection.close();
			}
		}
		return list;
	}
	
	/**
	 * 通过配置SQL的XML查询数据库,返回List
	 * @param xmlName
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-8 
	 */
	public List executeQueryXmlSql(String xmlName) throws Exception{
		SqlXml xml = new SqlXml(xmlName);
		String sql = xml.getSql();
		String db = xml.getDatabase();
		if(db != null){
			if(!db.equals(this.database)){
				throw new Exception("目标数据库不一致!");
			}else{
				this.database = db;
			}
		}
		return executeQuery(sql,null);
	}
	
	/**
	 * 通过配置SQL的XML查询数据库,返回List
	 * @param xmlName
	 * @param para
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-8 
	 */
	public List executeQueryXmlSql(String xmlName, Object[] para) throws Exception{
		SqlXml xml = new SqlXml(xmlName);
		String sql = xml.getSql();
		String db = xml.getDatabase();
		if(db != null){
			if(!db.equals(this.database)){
				throw new Exception("目标数据库不一致!");
			}else{
				this.database = db;
			}
		}
		return executeQuery(sql,para);
	}
	
	/**
	 * 通过配置SQL的XML查询数据库,返回List,传入值Map的key必须与XML中的参数code一致
	 * @param xmlName
	 * @param parameterMap
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-17
	 */
	public List executeQueryXmlSql(String xmlName, Map parameterMap) throws Exception{
		SqlXml sqlxml = new SqlXml(xmlName);
		String sql = sqlxml.getSql();
		String db = sqlxml.getDatabase();
		if(db != null){
			if(!db.equals(this.database)){
				throw new Exception("目标数据库不一致!");
			}else{
				this.database = db;
			}
		}
		SqlXml.Param[] params = sqlxml.getParameters();
		Object[] para = new Object[params.length];
		for (int i = 0; i < params.length; i++) {
			para[params[i].order-1] = parameterMap.get(params[i].code);
		}
		return executeQuery(sql,para);
	}
	
	public static String getPermaryKey(){
		UUID id = UUID.randomUUID();
		return id.toString();
	}
	/**
	 * 开始事务
	 * @throws SQLException
	 * @author hanwei
	 * @update 2011-6-9
	 */
	public void beginTransaction() throws SQLException{
		connection = getConnection(database);
		connection.setAutoCommit(false);
		//试解决:事务(进程 ID 367)与另一个进程被死锁在 锁 资源上,并且已被选作死锁牺牲品。请重新运行该事务。
		//connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
		//System.out.println("开始事务");
	}
	
	/**
	 * 提交事务,关闭事务
	 * @throws SQLException
	 * @author hanwei
	 * @update 2011-6-9
	 */
	public void endTransaction() throws SQLException{
		if(connection != null && !connection.isClosed()){
			connection.commit();
			connection.close();
			//System.out.println("提交事务,关闭事务");
		}
	}
	
	/**
	 * 回滚事务
	 * @throws SQLException
	 * @author hanwei
	 * @update 2011-6-16
	 */
	public void rollbackTransaction(){
		try {
			if(connection != null && !connection.isClosed()){
				connection.rollback();
				//System.out.println("提交事务,关闭事务");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 执行更新SQL
	 * @param sql
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-9
	 */
	public int executeUpdate(String sql) throws Exception{
		return executeUpdate(sql,null);
	}
	
	/**
	 * 更新数据,sql为insert或update
	 * @param sql
	 * @param para
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-8 
	 */
	public int executeUpdate(String sql, Object[] para) throws Exception{
		int retrunInt = 0;
		boolean doTransaction = false;//是否在本方法内完成事务,默认否
		if(connection == null || connection.isClosed()){
			connection = null;
			connection = getConnection(database);
			connection.setAutoCommit(false);
			doTransaction = true;
		}
		try {
			PreparedStatement ps = connection.prepareStatement(sql);
			if(para!=null){
				for(int i=0,l=para.length;i<l;i++){
					if(para[i] instanceof Date){
						long time = ((Date)para[i]).getTime();
						ps.setTimestamp(i+1, new java.sql.Timestamp(time));
					}else{
						ps.setObject(i+1, para[i]);
					}
				}
			}
			retrunInt = ps.executeUpdate();
			if(doTransaction){
				connection.commit();
			}
			if(doTransaction){
				ps.close();
				connection.close();
			}
		} catch (SQLException e) {
			if(connection!=null && !connection.isClosed()){
				connection.rollback();
			}
			e.printStackTrace();
			throw e;
		} finally{
			if(doTransaction && connection!=null && !connection.isClosed()){
				connection.close();//并不是真正的关闭,而是还回连接池
			}
		}
		return retrunInt;
	}
	
	/**
	 * 执行XML文件中的更新SQL
	 * @param xmlName
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-9
	 */
	public int executeUpdateXmlSql(String xmlName) throws Exception{
		SqlXml xml = new SqlXml(xmlName);
		String sql = xml.getSql();
		String db = xml.getDatabase();
		if(db != null){
			if(!db.equals(this.database)){
				throw new Exception("目标数据库不一致!");
			}else{
				this.database = db;
			}
		}
		return executeUpdate(sql,null);
	}
	
	/**
	 * 执行XML文件中的更新SQL
	 * @param xmlName
	 * @param para
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-9
	 */
	public int executeUpdateXmlSql(String xmlName, Object[] para) throws Exception{
		SqlXml sqlxml = new SqlXml(xmlName);
		if(sqlxml.getParameterSize() != para.length){
			if(connection != null && !connection.isClosed()){
				connection.rollback();
			}
			throw new Exception("传入的参数数目不正确!");
		}
		String sql = sqlxml.getSql();
		String db = sqlxml.getDatabase();
		if(db != null){
			if(!db.equals(this.database)){
				throw new Exception("目标数据库不一致!");
			}else{
				this.database = db;
			}
		}
		return executeUpdate(sql,para);
	}
	
	/**
	 * 执行XML文件中的更新SQL,传入值Map的key必须与XML中的参数code一致
	 * @param xmlName
	 * @param parameterMap
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-17
	 */
	public int executeUpdateXmlSql(String xmlName, Map parameterMap) throws Exception{
		SqlXml sqlxml = new SqlXml(xmlName);
		String sql = sqlxml.getSql();
//		System.out.println("sql"+sql);
		String db = sqlxml.getDatabase();
		if(db != null){
			if(!db.equals(this.database)){
				throw new Exception("目标数据库不一致!");
			}else{
				this.database = db;
			}
		}
		SqlXml.Param[] params = sqlxml.getParameters();
		Object[] para = new Object[params.length];
		for (int i = 0; i < params.length; i++) {
			para[params[i].order-1] = parameterMap.get(params[i].code);
		}
		return executeUpdate(sql,para);
	}
	
	/**
	 * 批量更新数据,List的元素为Object[]
	 * @param sql
	 * @param list
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-8 
	 */
	public int[] executeUpdateBatch(String sql, List list) throws Exception{
		int[] retrunInt;
		boolean doTransaction = false;//是否在本方法内完成事务,默认否
		if(connection == null || connection.isClosed()){
			connection = null;
			connection = getConnection(database);
			connection.setAutoCommit(false);
			doTransaction = true;
		}
		try {
			PreparedStatement ps = connection.prepareStatement(sql);
			for (int index = 0; index < list.size(); index++) {
				Object[] para = (Object[]) list.get(index);
				if(para!=null)
				for(int i=0,l=para.length;i<l;i++){
					if(para[i] instanceof Date){
						long time = ((Date)para[i]).getTime();
						ps.setTimestamp(i+1, new java.sql.Timestamp(time));
					}else{
						ps.setObject(i+1, para[i]);
					}
				}
				ps.addBatch();
			}
			retrunInt = ps.executeBatch();
			if(doTransaction){
				connection.commit();
			}
			ps.close();
			if(doTransaction){
				connection.close();
			}
		} catch (SQLException e) {
			if(connection!=null && !connection.isClosed()){
				connection.rollback();
			}
			e.printStackTrace();
			throw e;
		} finally{
			if(doTransaction && connection!=null && !connection.isClosed()){
				connection.close();//并不是真正的关闭,而是还回连接池
			}
		}
		return retrunInt;
	}
	
	/**
	 * 根据XML中的SQL批量更新数据,List的元素为Object[]
	 * @param xmlName
	 * @param list
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-9
	 */
	public int[] executeUpdateBatchXmlSql(String xmlName, List list) throws Exception{
		SqlXml xml = new SqlXml(xmlName);
		String sql = xml.getSql();
		String db = xml.getDatabase();
		if(db != null){
			if(!db.equals(this.database)){
				throw new Exception("目标数据库不一致!");
			}else{
				this.database = db;
			}
		}
		return executeUpdateBatch(sql,list);
	}
	
	/**
	 * 调用存储过程
	 * @param procedure
	 * @param param
	 * @param outNum
	 * @return
	 * @throws Exception
	 * @author hanwei
	 * @update 2011-6-8 
	 */
	public static List callProcedure(String procedure, List param, int outNum, String database)
    throws Exception{
        StringBuffer callBuf = new StringBuffer();
        callBuf.append("{call ");
        callBuf.append(procedure);
        callBuf.append("(");
        if (param != null){
            for (int i = 0; i < param.size(); i++){
                if (i == (param.size() - 1))
                    callBuf.append("?");
                else
                    callBuf.append("?,");
            }
        }
        callBuf.append(")}");
        String sql = callBuf.toString();
        
        Connection conn = getConnection(database);
        CallableStatement cs = conn.prepareCall(sql);
        if (param != null){
            for (int i = 0; i < param.size(); i++){
                Object arg = param.get(i);
                if (arg instanceof Integer)
                    cs.setInt(i + 1, Integer.parseInt(arg.toString()));
                else if (arg instanceof String)
                	cs.setString(i + 1, arg.toString());
                else if (arg instanceof Float)
                    cs.setFloat(i + 1, Float.parseFloat(arg.toString()));
                else if (arg instanceof Date){
                	Date date = (Date)arg;
                	cs.setTimestamp(i+1, new java.sql.Timestamp(date.getTime()));
                }else
                    cs.setObject(i + 1, arg.toString());
            }
        }
        
        for (int i = param.size()-outNum; i < param.size(); i++){
        	cs.registerOutParameter(i+1, Types.VARCHAR);
        }
        cs.execute();
        List list = new ArrayList(outNum);
        for (int j = param.size() - outNum; j < param.size(); j++){
            list.add(cs.getObject(j+1));
        }
        return list;
    }
	
	public static void main(String[] args) throws Exception{
		
		//插入示例、修改示例、事务示例
		/*Object[] para = new Object[10];
		para[0] = DatabaseUtil.getPermaryKey();
		para[1] = "测试患者";
		para[2] = "身份证号";
		para[3] = "男";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
		para[4] = sdf.format(new Date());
		para[5] = "矿工";
		para[6] = "地球村";
		para[7] = "021";
		para[8] = "139";
		para[9] = "DOCTOR_ID";
		DatabaseUtil dbUtil = new DatabaseUtil();
		try {
			dbUtil.beginTransaction();
			int insertInt = dbUtil.executeUpdateXmlSql("hyper_card_add", para);
			int updateInt = dbUtil.executeUpdateXmlSql("hyper_card_update"
					,new Object[]{"6666665","13888888885",para[0]});
			dbUtil.endTransaction();
		} catch (Exception e) {
			dbUtil.rollbackTransaction();
			e.printStackTrace();
		}*/
		
		//插入Map示例
		/*Map map = new HashMap();
		map.put("card_id", DatabaseUtil.getPermaryKey());
		map.put("NAME", "姓名1");
		map.put("sfzh", "身份证号");
		map.put("gender", "男");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
		map.put("birthdate", sdf.format(new Date()));
		map.put("profession", "矿工");
		map.put("address", "地球村");
		map.put("phone", "021");
		map.put("cell_phone", "139");
		map.put("doctor_id", "DOCTOR_ID");
		DatabaseUtil dbUtil = new DatabaseUtil();
		try {
			int insertInt = dbUtil.executeUpdateXmlSql("hyper_card_add", map);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		
		/*JSONObject json = new JSONObject();
		json.put("VISIT_ID", DatabaseUtil.getPermaryKey());
		json.put("CARD_ID", "1");
		Map map = (Map) json.toBean(json, Map.class);
		map.put("VISIT_DATE", new Date());
		Object visit_date = map.get("VISIT_DATE");
		Map map = new HashMap();
		map.put("VISIT_ID", DatabaseUtil.getPermaryKey());
		map.put("CARD_ID", "1");
		map.put("VISIT_DATE", new Date());
		DatabaseUtil dbUtil = new DatabaseUtil();
		try {
			int insertInt = dbUtil.executeUpdateXmlSql("hyper_visit_add", map);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		
		//分页查询示例
		SqlXml xml = new SqlXml("hyper_card_query");
		String sql = xml.getSqlPage(1000, 1);
		System.out.println(sql);
		JSONArray array = JSONArray.fromObject(
				DatabaseUtil.queryForList(sql,new Object[]{"%2011%"},DBConstant.DATABASE_CONNECTION_PLATFORM));
		System.out.println(array.toString());
		
		/*Map map = new HashMap();
		map.put("PHONE", null);
		JSONObject obj = JSONObject.fromObject(map,new JsonConfig());
		System.out.println(obj.get("PHONE")==null);*/
		
		
		/*Map parameterMap = new HashMap();
		parameterMap.put("CARD_NO", "20110614");
//		parameterMap.put("CARD_NO", "%"+parameterMap.get("CARD_NO")+"%");
		JSONArray array = JSONArray.fromObject(
				DatabaseUtil.queryForListXmlSql("hyper_card_query", parameterMap));
		System.out.println(array.toString());*/
		
		
	}

}
HTTP用户基本认证Filter
package com.neusoft.android.common.filter;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.neusoft.android.common.database.DatabaseUtil;
import com.neusoft.android.common.sql.SqlXml;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;

public class AuthenticationFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        System.out.println("请求路径:"+httpRequest.getServletPath());
        
        //登录时不认证
        if("/servlet/LoginServlet".equals(httpRequest.getServletPath())){
        	chain.doFilter( httpRequest, httpResponse );
            return;
        }
        //检查更新时不认证
        if("/servlet/GetServerVersionServlet".equals(httpRequest.getServletPath())){
        	chain.doFilter( httpRequest, httpResponse );
            return;
        }
        //下载更新时不认证
        if("/servlet/GetUpgradedAppServlet".equals(httpRequest.getServletPath())){
        	chain.doFilter( httpRequest, httpResponse );
            return;
        }
        /*String realPath = httpRequest.getSession().getServletContext()
		.getRealPath(ServerVersionConfig.CONFIG_XML_PATH);
        ServerVersionConfig versionConfig = ServerVersionConfig.getInstance(realPath);
        if(versionConfig.app_path.equals(httpRequest.getServletPath())){
        	chain.doFilter(httpRequest, httpResponse);
            return;
        }*/
        
        //HTTP Basic access authentication
        String auth = httpRequest.getHeader("Authorization");
        if ( auth != null ) {
            int index = auth.indexOf( ' ' );
            if ( index > 0 ) {
                String[] credentials = null;
				try {
					credentials = StringUtils.split(new String(
							Base64.decode(auth.substring(index)), "UTF-8"), ':' );
				} catch (Base64DecodingException e) {
					e.printStackTrace();
				}
				
                if ( credentials != null && credentials.length == 2 
                		&& validateAccount(credentials[0],credentials[1])){
                    chain.doFilter( httpRequest, httpResponse );
                    return;
                }
            }
        }
 
        httpResponse.setHeader("WWW-Authenticate", "BASIC   realm=\"FollowUpVisitServer - neusoft - shanghai yangpu\" ");
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
	}

	public void init(FilterConfig arg0) throws ServletException {

	}
	
	/**
	 * 验证帐号密码合法性
	 * @param account
	 * @param password
	 * @return
	 * @author hanwei
	 * @update 2011-6-9
	 */
	private boolean validateAccount(String account,String password){
		if(account == null || account.trim().length()==0 
				||password == null || password.trim().length()==0 ){
			return false;
		}
		boolean validated = false;
		Connection conn = null;
		try {
			conn = DatabaseUtil.getConnection();
//			String sql = "select USER_PASSWORD from DOCTOR_USER t where t.USER_ACCOUNT=?";
			SqlXml xml = new SqlXml("authentication");
			String sql = xml.getSql();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, account);
			ResultSet rs = ps.executeQuery();
			if(rs.next()){
				validated = password.equals(rs.getString("USER_PASSWORD"));
				conn.close();
				if(validated){
					System.out.println("帐号已认证:"+account+"");
				}else{
					System.out.println("密码错:"+account+"");
				}
			}else{
				conn.close();
				System.out.println("无此帐号:"+account+"");
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(conn!=null && !conn.isClosed()){
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return validated;
	}

}
android新版本下载
package com.neusoft.yangpu.followupvisit.setting;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.neusoft.yangpu.followupvisit.util.Utils;

public class UpgradeAppTask extends AsyncTask<Object,Integer,Integer>{

	public UpgradeAppTask(Context context,Handler handler) {
		super();
		this.context = context;
		this.MainHandler = handler;
	}

	private final static int MSG_UPGRADE_APP_SHOW_PROGRESS = 201;
	private final static int MSG_UPGRADE_APP_HIDE_PROGRESS = 202;
	private final static int MSG_UPGRADE_APP_SET_PROGRESS = 203;
	private final static int MSG_UPGRADE_APP_URL_404 = 204;
	public final static int MSG_UPGRADE_APP_FINISH = 999991;
	
	private Context context;
	private Handler handler;
	private Handler MainHandler;
	private ProgressDialog progressDialog;
	
	//文件存储
	private File updateDir = null;
	private File updateFile = null;
	
	@Override
	protected void onPreExecute() {
		handler = new Handler(Looper.getMainLooper()){
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_UPGRADE_APP_SHOW_PROGRESS:
					progressDialog = new ProgressDialog(context);
					progressDialog.setTitle("正在下载新版本");
					progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
					progressDialog.setMax(100);
					progressDialog.setCancelable(false);
					progressDialog.setProgress(0);
					progressDialog.show();
					break;
				case MSG_UPGRADE_APP_HIDE_PROGRESS:
					progressDialog.dismiss();
					Utils.showToast("下载超时,请重试!",context);
					break;
				case MSG_UPGRADE_APP_SET_PROGRESS:
					progressDialog.setProgress(msg.arg1);
					break;
				case MSG_UPGRADE_APP_URL_404:
					progressDialog.dismiss();
					Utils.showToast("版本路径不存在,下载失败!",context);
					break;
				case MSG_UPGRADE_APP_FINISH:
					progressDialog.dismiss();
					Toast.makeText(context, "新版本软件已下载,请确定安装。"
							, Toast.LENGTH_SHORT).show();
					Uri uri = Uri.fromFile(updateFile);
	                Intent installIntent = new Intent(Intent.ACTION_VIEW);
	                installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
	                context.startActivity(installIntent);
					if(MainHandler != null){
						Message msg1 = handler.obtainMessage(MSG_UPGRADE_APP_FINISH);
						msg1.obj = msg.obj;
						MainHandler.sendMessage(msg1);
					}
					break;
				}
				super.handleMessage(msg);
			}
		};
		
		//创建文件
	    if(android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())){
	        updateDir = new File(Environment.getExternalStorageDirectory()
	        		,UpgradeVersionConfig.NEW_VERSION_DOWNLOAD_DIR);
	        updateFile = new File(updateDir.getPath()
	        		,UpgradeVersionConfig.NEW_VERSION_FILE_NAME);
	    }
		super.onPreExecute();
	}
	
	/* params[0]: context, params[1]:paramArray
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected Integer doInBackground(Object... params) {
		handler.sendEmptyMessage(MSG_UPGRADE_APP_SHOW_PROGRESS);
		String urlStr = (String) params[0];
		
        //int currentSize = 0;
        int totalSize = 0;
        int updateTotalSize = 0;
        
        HttpURLConnection httpConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        
        try {
        	/*SharedPreferences pref = Utils.getPref(context);
    		String account = pref.getString(Constant.user_account, null);
    		String encodedPwd = pref.getString(Constant.user_password, null);
    		String password = null;
    		if(encodedPwd!=null){
    			password = new String(Base64.decode(encodedPwd));
    		}
    		String userPassword = account+":"+password;
            String encoding = new String(Base64.encode(userPassword.getBytes())).trim();*/
            
          //增加权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
            if(!updateDir.exists()){
                updateDir.mkdirs();
            }
            if(!updateFile.exists()){
                updateFile.createNewFile();
            }
    		
            URL url = new URL(urlStr);
            httpConnection = (HttpURLConnection)url.openConnection();
            httpConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
            //httpConnection.setRequestProperty("Authorization", "Basic " + encoding);
            /*FileInputStream fis = new FileInputStream(updateFile);
            currentSize = fis.available();
            if(currentSize > 0) {
                httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-");
            }
            */
            httpConnection.setConnectTimeout(10000);
            httpConnection.setReadTimeout(20000);
            updateTotalSize = httpConnection.getContentLength();
            if (httpConnection.getResponseCode() == 404) {
            	handler.sendEmptyMessage(MSG_UPGRADE_APP_URL_404);
                this.cancel(true);
            }
            is = httpConnection.getInputStream();
            fos = new FileOutputStream(updateFile, false);
            byte buffer[] = new byte[4096];
            int readsize = 0;
            while((readsize = is.read(buffer)) > 0){
                fos.write(buffer, 0, readsize);
                totalSize += readsize;
                publishProgress((int)totalSize*100/updateTotalSize);
            }
        }catch (IOException e) {
			Log.e("debug tag", "超时", e);
			handler.sendEmptyMessage(MSG_UPGRADE_APP_HIDE_PROGRESS);
			this.cancel(true);
			return 0;
		} finally {
            if(httpConnection != null) {
                httpConnection.disconnect();
            }
            if(is != null) {
                try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
            if(fos != null) {
                try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
        }
        return updateTotalSize;
			
	}
	
	protected void onProgressUpdate(Integer... values){
		Message msg = handler.obtainMessage(MSG_UPGRADE_APP_SET_PROGRESS);
		msg.arg1 = values[0];
		handler.sendMessage(msg);
	}
	
	protected void onPostExecute(Integer result){
		if(result != null){
			Message msg = handler.obtainMessage(MSG_UPGRADE_APP_FINISH);
			msg.arg1 = result;
			handler.sendMessage(msg);
		}
	}
}
android检查最新版本
package com.neusoft.yangpu.followupvisit.setting;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.neusoft.yangpu.followupvisit.util.HttpUtil;
import com.neusoft.yangpu.followupvisit.util.NetworkUtil;
import com.neusoft.yangpu.followupvisit.util.Utils;

public class UpgradeCheckThread extends Thread {

	public final static int MSG_NO_NEW_VERSION = 1001;
	public final static int MSG_MAIN_VERSION_UPGRADE = 1002;
	public final static int MSG_NORMAL_VERSION_UPGRADE = 1003;
	
	private Context context;
	private Handler MainHandler;
	
	public UpgradeCheckThread(Context context,Handler handler) {
		this.context = context;
		this.MainHandler = handler;
	}
	private Handler handler = new Handler(Looper.getMainLooper()){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_NO_NEW_VERSION:
				Utils.showToast("当前软件已是最新版本。",context);
				break;
			case MSG_MAIN_VERSION_UPGRADE:
				final UpgradeVersionConfig version = (UpgradeVersionConfig) msg.obj;
				//Utils.showToast("发现新版本,正在下载。。。",context);
				//String url = NetworkUtil.getServerBaseURL(context)+version.app_path.replaceFirst("/", "");
				//new UpgradeAppTask(context, null).execute(url);
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setTitle("版本"+version.version_name+"更新说明")
					.setMessage(version.change_log)
				    .setCancelable(false)
				    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
				         public void onClick(DialogInterface dialog, int id) {
				        	 String url = NetworkUtil.getServerBaseURL(context)
				        	 	+"servlet/GetUpgradedAppServlet";
				        	 	//+ version.app_path.replaceFirst("/", "");
							 new UpgradeAppTask(context, MainHandler).execute(url);
				         }
				    });
				AlertDialog alert = builder.create();
				alert.show();
				break;
			case MSG_NORMAL_VERSION_UPGRADE:
				final UpgradeVersionConfig version1 = (UpgradeVersionConfig) msg.obj;
				AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
				builder1.setTitle("版本"+version1.version_name+"更新说明")
					.setMessage(version1.change_log)
				    .setCancelable(false)
				    .setNegativeButton("取消更新", new DialogInterface.OnClickListener() {
				         public void onClick(DialogInterface dialog, int id) {
				        	 dialog.dismiss();
				         }
				    })
				    .setPositiveButton("确定更新", new DialogInterface.OnClickListener() {
				         public void onClick(DialogInterface dialog, int id) {
				        	 String url = NetworkUtil.getServerBaseURL(context)
				        	 	+"servlet/GetUpgradedAppServlet";
				        	 //	+ version1.app_path.replaceFirst("/", "");
							 new UpgradeAppTask(context, MainHandler).execute(url);
				         }
				    });
				builder1.create().show();
				break;
			}
		}
	};
	
	@Override
	public void run() {
		String url = NetworkUtil.getServerBaseURL(context)+"servlet/GetServerVersionServlet";
		String jsonStr = null;
		try {
			jsonStr = HttpUtil.queryStringPost(url, context);
			if(jsonStr == null ){
				
				return;
			}
			JSONObject dataObj = new JSONObject(jsonStr);
			UpgradeVersionConfig version = new UpgradeVersionConfig();
			version.version_code = dataObj.getInt(UpgradeVersionConfig.TAG_VERSION_NORMEL);
			version.version_name = dataObj.getString(UpgradeVersionConfig.TAG_VERSION_NAME);
			version.version_main = dataObj.getInt(UpgradeVersionConfig.TAG_VERSION_MAIN);
			version.change_log = dataObj.getString(UpgradeVersionConfig.TAG_CHANGE_LOG);
			version.app_path = dataObj.getString(UpgradeVersionConfig.TAG_APP_PATH);
			
			int server_version_code = version.version_code;
			int local_version_code = Utils.getVersionCode(context);
			if(server_version_code != local_version_code){
				int server_main_version = version.version_main;
				Message msg = handler.obtainMessage();
				if(server_main_version > Utils.getMainVersionNumber()){
					msg.what = MSG_MAIN_VERSION_UPGRADE;
				}else{
					msg.what = MSG_NORMAL_VERSION_UPGRADE;
				}
				msg.obj = version;
				handler.sendMessage(msg);
			}else{
				handler.sendEmptyMessage(MSG_NO_NEW_VERSION);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	
}
android本地数据库数据更新
package com.neusoft.yangpu.followupvisit.setting;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.neusoft.yangpu.followupvisit.sqlite.DatabaseUtil;
import com.neusoft.yangpu.followupvisit.sqlite.TableColumnConfigUtil;
import com.neusoft.yangpu.followupvisit.util.HttpUtil;
import com.neusoft.yangpu.followupvisit.util.NetworkUtil;

public class UpdateDataTask extends AsyncTask<Object,Integer,Integer>{

	public UpdateDataTask(Context context,Handler handler) {
		super();
		this.context = context;
		this.MainHandler = handler;
	}

	private final static int MSG_UPDATE_DATA_SHOW_PROGRESS = 201;
	private final static int MSG_UPDATE_DATA_HIDE_PROGRESS = 202;
	private final static int MSG_UPDATE_DATA_SET_PROGRESS = 203;
	public final static int MSG_UPDATE_DATA_FINISH = 999999;
	
	private Context context;
	private Handler handler;
	private Handler MainHandler;
	private ProgressDialog progressDialog;
	
	@Override
	protected void onPreExecute() {
		handler = new Handler(Looper.getMainLooper()){
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_UPDATE_DATA_SHOW_PROGRESS:
					progressDialog = new ProgressDialog(context);
					progressDialog.setTitle("更新进度");
					progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
					progressDialog.setMax(100);
					progressDialog.setCancelable(false);
					progressDialog.setProgress(0);
					progressDialog.show();
					break;
				case MSG_UPDATE_DATA_HIDE_PROGRESS:
					progressDialog.dismiss();
					break;
				case MSG_UPDATE_DATA_SET_PROGRESS:
					progressDialog.setProgress(msg.arg1);
					break;
				case MSG_UPDATE_DATA_FINISH:
					progressDialog.dismiss();
					int length =  msg.arg1;
					Toast.makeText(context, "成功更新"+length+"条数据。"
							, Toast.LENGTH_SHORT).show();
					if(MainHandler != null){
						Message msg1 = handler.obtainMessage(MSG_UPDATE_DATA_FINISH);
						msg1.arg1 = length;
						MainHandler.sendMessage(msg1);
					}
					break;
				}
				super.handleMessage(msg);
			}
		};
		super.onPreExecute();
	}
	
	/* params[0]: context, params[1]:paramArray
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected Integer doInBackground(Object... params) {
		int data_size = 0;
		try {
			JSONArray paramArray = (JSONArray) params[0];
			Map map = new HashMap();
			map.put("update_tables", paramArray.toString());
			String url = NetworkUtil.getServerBaseURL(context)+"servlet/UpdateDataServlet";
			String jsonStr = HttpUtil.queryStringPost(url, context, map);
			
			handler.sendEmptyMessage(MSG_UPDATE_DATA_SHOW_PROGRESS);
			
			DatabaseUtil dbUtil = new DatabaseUtil(context);
			dbUtil.beginTransaction();
			// 删除本地SQLite数据库表中的数据
			for (int i = 0; i < paramArray.length(); i++){
				JSONObject paramObj = paramArray.getJSONObject(i);
				String tableName = paramObj.getString(TableColumnConfigUtil.TABLE_NAME);
				dbUtil.clearTableData(tableName);
			}
			
			JSONObject dataObj = new JSONObject(jsonStr);
			data_size = dataObj.getInt("data_size");
			int count = 0;
			for (int i = 0; i < paramArray.length(); i++) {
				JSONObject paramObj = paramArray.getJSONObject(i);
				String tableId = paramObj.getString(TableColumnConfigUtil.TABLE_ID);
				String tableName = paramObj.getString(TableColumnConfigUtil.TABLE_NAME);
//				Log.d("UpdateDataActivity", "tableName:"+tableName);
				JSONArray data = dataObj.getJSONArray(tableId);
				for (int j = 0; j < data.length(); j++) {
					count++;
					JSONObject obj = data.getJSONObject(j);
//					Log.d("UpdateDataActivity", "row:"+obj.toString());
					ContentValues values = new ContentValues();
					Iterator keyIt = obj.keys();
					while (keyIt.hasNext()) {
						String key = (String) keyIt.next();
						values.put(key, obj.getString(key));
					}
					dbUtil.insert(tableName, values);
					publishProgress(count* 100 / data_size);
				}
			}
			dbUtil.endTransaction();
		} catch (IOException e) {
			Log.e("debug tag", "超时", e);
			handler.sendEmptyMessage(MSG_UPDATE_DATA_HIDE_PROGRESS);
			this.cancel(true);
			return 0;
		} catch (JSONException e) {
			handler.sendEmptyMessage(MSG_UPDATE_DATA_HIDE_PROGRESS);
			this.cancel(true);
			Log.e("debug tag", e.getMessage(), e);
			return 0;
		}
		return data_size;
	}
	
	protected void onProgressUpdate(Integer... values){
		Message msg = handler.obtainMessage(MSG_UPDATE_DATA_SET_PROGRESS);
		msg.arg1 = values[0];
		handler.sendMessage(msg);
	}
	
	protected void onPostExecute(Integer result){
		if(result != null){
			Message msg = handler.obtainMessage(MSG_UPDATE_DATA_FINISH);
			msg.arg1 = result;
			handler.sendMessage(msg);
		}
	}
}
Base64编码解码
package com.neusoft.yangpu.followupvisit.util;

/**
 * @author wudepeng
 *
 */
public class Base64 {
	private static final byte[] encodingTable = { (byte) 'A', (byte) 'B',
			(byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',
			(byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L',
			(byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q',
			(byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V',
			(byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a',
			(byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f',
			(byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k',
			(byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p',
			(byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',
			(byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z',
			(byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
			(byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',
			(byte) '+', (byte) '/' };
	private static final byte[] decodingTable;
	static {
		decodingTable = new byte[128];
		for (int i = 0; i < 128; i++) {
			decodingTable[i] = (byte) -1;
		}
		for (int i = 'A'; i <= 'Z'; i++) {
			decodingTable[i] = (byte) (i - 'A');
		}
		for (int i = 'a'; i <= 'z'; i++) {
			decodingTable[i] = (byte) (i - 'a' + 26);
		}
		for (int i = '0'; i <= '9'; i++) {
			decodingTable[i] = (byte) (i - '0' + 52);
		}
		decodingTable['+'] = 62;
		decodingTable['/'] = 63;
	}

	public static byte[] encode(byte[] data) {
		byte[] bytes;
		int modulus = data.length % 3;
		if (modulus == 0) {
			bytes = new byte[(4 * data.length) / 3];
		} else {
			bytes = new byte[4 * ((data.length / 3) + 1)];
		}
		int dataLength = (data.length - modulus);
		int a1;
		int a2;
		int a3;
		for (int i = 0, j = 0; i < dataLength; i += 3, j += 4) {
			a1 = data[i] & 0xff;
			a2 = data[i + 1] & 0xff;
			a3 = data[i + 2] & 0xff;
			bytes[j] = encodingTable[(a1 >>> 2) & 0x3f];
			bytes[j + 1] = encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f];
			bytes[j + 2] = encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f];
			bytes[j + 3] = encodingTable[a3 & 0x3f];
		}
		int b1;
		int b2;
		int b3;
		int d1;
		int d2;
		switch (modulus) {
		case 0: /* nothing left to do */
			break;
		case 1:
			d1 = data[data.length - 1] & 0xff;
			b1 = (d1 >>> 2) & 0x3f;
			b2 = (d1 << 4) & 0x3f;
			bytes[bytes.length - 4] = encodingTable[b1];
			bytes[bytes.length - 3] = encodingTable[b2];
			bytes[bytes.length - 2] = (byte) '=';
			bytes[bytes.length - 1] = (byte) '=';
			break;
		case 2:
			d1 = data[data.length - 2] & 0xff;
			d2 = data[data.length - 1] & 0xff;
			b1 = (d1 >>> 2) & 0x3f;
			b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;
			b3 = (d2 << 2) & 0x3f;
			bytes[bytes.length - 4] = encodingTable[b1];
			bytes[bytes.length - 3] = encodingTable[b2];
			bytes[bytes.length - 2] = encodingTable[b3];
			bytes[bytes.length - 1] = (byte) '=';
			break;
		}
		return bytes;
	}

	public static byte[] decode(byte[] data) {
		byte[] bytes;
		byte b1;
		byte b2;
		byte b3;
		byte b4;
		data = discardNonBaseytes(data);
		if (data[data.length - 2] == '=') {
			bytes = new byte[(((data.length / 4) - 1) * 3) + 1];
		} else if (data[data.length - 1] == '=') {
			bytes = new byte[(((data.length / 4) - 1) * 3) + 2];
		} else {
			bytes = new byte[((data.length / 4) * 3)];
		}
		for (int i = 0, j = 0; i < (data.length - 4); i += 4, j += 3) {
			b1 = decodingTable[data[i]];
			b2 = decodingTable[data[i + 1]];
			b3 = decodingTable[data[i + 2]];
			b4 = decodingTable[data[i + 3]];
			bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));
			bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));
			bytes[j + 2] = (byte) ((b3 << 6) | b4);
		}
		if (data[data.length - 2] == '=') {
			b1 = decodingTable[data[data.length - 4]];
			b2 = decodingTable[data[data.length - 3]];
			bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));
		} else if (data[data.length - 1] == '=') {
			b1 = decodingTable[data[data.length - 4]];
			b2 = decodingTable[data[data.length - 3]];
			b3 = decodingTable[data[data.length - 2]];
			bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));
			bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));
		} else {
			b1 = decodingTable[data[data.length - 4]];
			b2 = decodingTable[data[data.length - 3]];
			b3 = decodingTable[data[data.length - 2]];
			b4 = decodingTable[data[data.length - 1]];
			bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));
			bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));
			bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);
		}
		return bytes;
	}

	public static byte[] decode(String data) {
		byte[] bytes;
		byte b1;
		byte b2;
		byte b3;
		byte b4;
		data = discardNonBasehars(data);
		if (data.charAt(data.length() - 2) == '=') {
			bytes = new byte[(((data.length() / 4) - 1) * 3) + 1];
		} else if (data.charAt(data.length() - 1) == '=') {
			bytes = new byte[(((data.length() / 4) - 1) * 3) + 2];
		} else {
			bytes = new byte[((data.length() / 4) * 3)];
		}
		for (int i = 0, j = 0; i < (data.length() - 4); i += 4, j += 3) {
			b1 = decodingTable[data.charAt(i)];
			b2 = decodingTable[data.charAt(i + 1)];
			b3 = decodingTable[data.charAt(i + 2)];
			b4 = decodingTable[data.charAt(i + 3)];
			bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));
			bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));
			bytes[j + 2] = (byte) ((b3 << 6) | b4);
		}
		if (data.charAt(data.length() - 2) == '=') {
			b1 = decodingTable[data.charAt(data.length() - 4)];
			b2 = decodingTable[data.charAt(data.length() - 3)];
			bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));
		} else if (data.charAt(data.length() - 1) == '=') {
			b1 = decodingTable[data.charAt(data.length() - 4)];
			b2 = decodingTable[data.charAt(data.length() - 3)];
			b3 = decodingTable[data.charAt(data.length() - 2)];
			bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));
			bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));
		} else {
			b1 = decodingTable[data.charAt(data.length() - 4)];
			b2 = decodingTable[data.charAt(data.length() - 3)];
			b3 = decodingTable[data.charAt(data.length() - 2)];
			b4 = decodingTable[data.charAt(data.length() - 1)];
			bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));
			bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));
			bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);
		}
		return bytes;
	}

	private static byte[] discardNonBaseytes(byte[] data) {
		byte[] temp = new byte[data.length];
		int bytesCopied = 0;
		for (int i = 0; i < data.length; i++) {
			if (isValidBaseyte(data[i])) {
				temp[bytesCopied++] = data[i];
			}
		}
		byte[] newData = new byte[bytesCopied];
		System.arraycopy(temp, 0, newData, 0, bytesCopied);
		return newData;
	}

	private static String discardNonBasehars(String data) {
		StringBuffer sb = new StringBuffer();
		int length = data.length();
		for (int i = 0; i < length; i++) {
			if (isValidBaseyte((byte) (data.charAt(i)))) {
				sb.append(data.charAt(i));
			}
		}
		return sb.toString();
	}

	private static boolean isValidBaseyte(byte b) {
		if (b == '=') {
			return true;
		} else if ((b < 0) || (b >= 128)) {
			return false;
		} else if (decodingTable[b] == -1) {
			return false;
		}
		return true;
	}
}
android HTTP请求工具类(HTTP基本认证)
package com.neusoft.yangpu.followupvisit.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

/**HTTP请求工具类
 * 使用基本用户认证方式、已处理超时异常和空响应异常、自动显示进度条(新建线程时可用)
 * @author hanwei
 *
 */
public class HttpUtil {
	public final static int HTTP_CONNECT_TIMEOUT = 10000;//超时时间(毫秒)
	
	public final static int HANDLE_MESSAGE_HTTP_REQUEST_TIMEOUT = 999;
	public final static int HANDLE_MESSAGE_HTTP_REQUEST_ERROR = 998;
	public final static int HANDLE_MESSAGE_SHOW_PROGRESS_DIALOG = 991;
	public final static int HANDLE_MESSAGE_HIDE_PROGRESS_DIALOG = 992;
	
	/**发送Post请求
	 * @param url
	 * @param context
	 * @return
	 * @throws IOException
	 */
	public static String queryStringPost(String url, Context context) 
		throws IOException{
		return queryStringPost(url,context,null);
	}
	
	/** 发送Post请求
	 * @param url
	 * @param context
	 * @param params
	 * @return
	 * @throws IOException
	 */
	public static String queryStringPost(String url, final Context context, Map params) 
		throws IOException{
		String result = null;
		
		//检查本地网络是否连接
		if(!NetworkUtil.checkNetworkConnected(context)){
			return null;
		}
		
		//Basic authentication 帐号和密码
		SharedPreferences pref = Utils.getPref(context);
		String account = pref.getString(Constant.user_account, null);
		String encodedPwd = pref.getString(Constant.user_password, null);
		String password = null;
		if(encodedPwd!=null){
			password = new String(Base64.decode(encodedPwd));
		}
		
		Handler handler = new Handler(Looper.getMainLooper()){
			ProgressDialog progressDialog;
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case HANDLE_MESSAGE_HTTP_REQUEST_TIMEOUT:
					progressDialog.dismiss();
					Utils.showToast("网络连接超时,请重试!",context);
					break;
				case HANDLE_MESSAGE_HTTP_REQUEST_ERROR:
					progressDialog.dismiss();
					Utils.showToast("网络连接出错!",context);
					break;
				case HANDLE_MESSAGE_SHOW_PROGRESS_DIALOG:
					progressDialog = ProgressDialog.show(context, "请稍候"
							, "正在加载。。。", false, false);
				    break;
				case HANDLE_MESSAGE_HIDE_PROGRESS_DIALOG:
					progressDialog.dismiss();
					break;
				}
			}
		};
		handler.sendEmptyMessage(HANDLE_MESSAGE_SHOW_PROGRESS_DIALOG);
		
		try {
			result =  doRequestPost(url,account,password,params);
			if(result == null){
				handler.sendEmptyMessage(HANDLE_MESSAGE_HTTP_REQUEST_ERROR);
			}
		} catch (IOException e) {
			handler.sendEmptyMessage(HANDLE_MESSAGE_HTTP_REQUEST_TIMEOUT);
			throw e;
		}
		handler.sendEmptyMessage(HANDLE_MESSAGE_HIDE_PROGRESS_DIALOG);
		
		return result;
	}
	
	/**发送Get请求,获得响应查询结果
	 * @param url
	 * @param context
	 * @return
	 * @throws IOException
	 */
	public static String queryStringGet(String url, Context context) 
		throws IOException{
		return queryStringGet(url,context,null);
	}
	/**发送Get请求,获得响应查询结果
	 * @param url
	 * @param context
	 * @return
	 * @throws IOException
	 */
	public static String queryStringGet(String url, final Context context, Map params) 
		throws IOException{
		String result = null;
		
		//检查本地网络是否连接
		if(!NetworkUtil.checkNetworkConnected(context)){
			return null;
		}
		
		//Basic authentication 帐号和密码
		SharedPreferences pref = Utils.getPref(context);
		String account = pref.getString(Constant.user_account, null);
		String encodedPwd = pref.getString(Constant.user_password, null);
		String password = null;
		if(encodedPwd!=null){
			password = new String(Base64.decode(encodedPwd));
		}
		
		Handler handler = new Handler(Looper.getMainLooper()){
			ProgressDialog progressDialog;
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case HANDLE_MESSAGE_HTTP_REQUEST_TIMEOUT:
					progressDialog.dismiss();
					Utils.showToast("网络连接超时,请重试!",context);
					break;
				case HANDLE_MESSAGE_HTTP_REQUEST_ERROR:
					progressDialog.dismiss();
					Utils.showToast("网络连接出错!",context);
					break;
				case HANDLE_MESSAGE_SHOW_PROGRESS_DIALOG:
					progressDialog = ProgressDialog.show(context, "请稍候"
							, "正在加载。。。", false, false);
				    break;
				case HANDLE_MESSAGE_HIDE_PROGRESS_DIALOG:
					progressDialog.dismiss();
					break;
				}
			}
		};
		handler.sendEmptyMessage(HANDLE_MESSAGE_SHOW_PROGRESS_DIALOG);
		
		try {
			result =  doRequestGet(url,account,password,params);
			if(result == null){
				handler.sendEmptyMessage(HANDLE_MESSAGE_HTTP_REQUEST_ERROR);
			}
		} catch (IOException e) {
			handler.sendEmptyMessage(HANDLE_MESSAGE_HTTP_REQUEST_TIMEOUT);
			throw e;
		}
		handler.sendEmptyMessage(HANDLE_MESSAGE_HIDE_PROGRESS_DIALOG);
		
		return result;
	}
	
	public static String doRequestPost(String url,String account,String password) 
		throws IOException{
		return doRequestPost(url,account,password,null);
	}
	
	public static String doRequestPost(String url,String account,String password,Map params) 
		throws IOException{
		return doRequest("POST",url,account,password,params);
	}
	
	public static String doRequestGet(String url,String account,String password) 
		throws IOException{
	    return doRequest("GET",url,account,password,null);
	}
	
	public static String doRequestGet(String url,String account,String password,Map params) 
		throws IOException{
        return doRequest("GET",url,account,password,params);
    }
	
	/**开始HTTP请求,并返回结果
	 * @param requestMethod
	 * @param urlString
	 * @param account
	 * @param password
	 * @param params
	 * @return
	 * @throws IOException
	 */
	public static String doRequest(String requestMethod,String urlString,String account,String password,Map params) 
	throws IOException{
		String result = null;
		String encoding = null;
		if(account!=null && password!=null){
			String userPassword = account+":"+password;
	        encoding = new String(Base64.encode(userPassword.getBytes())).trim();
		}
		
        URL url = new URL (urlString);
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setConnectTimeout(HTTP_CONNECT_TIMEOUT);
        
        if(encoding != null){
        	uc.setRequestProperty("Authorization", "Basic " + encoding);
        }
        uc.setRequestProperty("User-Agent", "Mozilla/5.0");
        
        uc.setDoInput(true);
        uc.setDoOutput(true);
        uc.setRequestMethod(requestMethod);
        
        if (params != null && !params.isEmpty()) {
        	StringBuffer buf = new StringBuffer();
        	Iterator keyIt = params.keySet().iterator();
        	while(keyIt.hasNext()){
        		String key = (String) keyIt.next();
        		buf.append("&").append(key).append("=").append(params.get(key));
        	}
        	buf.deleteCharAt(0);
            uc.getOutputStream().write(buf.toString().getBytes("UTF-8"));  
            uc.getOutputStream().close();  
        }
  
        InputStream content = uc.getInputStream();
        BufferedReader in = new BufferedReader (new InputStreamReader (content,"UTF-8"));
        result = "";
        String line;
        while ((line = in.readLine()) != null) {//
//        	Log.e("HttpUtil", "line:"+line);
        	result = result.concat(line.trim());
        }
        
        in.close();
//        Log.e("HttpUtil", "result:"+result);
        return result;
    }



	/**
	 * 本地网络是否已连接
	 * @param context
	 * @return
	 */
	public static boolean isNetworkConnected(Context context){
		boolean isConnected;
		SharedPreferences pref = context
			.getSharedPreferences(Constant.sharedPreferencesFileName, Context.MODE_PRIVATE);
		
		if(pref.contains(Constant.pref_isNetworkConnected) == false){
			ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	        NetworkInfo netInfo = cm.getActiveNetworkInfo();
	        if(netInfo == null){
	        	isConnected = false;
	        }else{
	        	isConnected = netInfo.isConnected();
	        }
		}else{
			isConnected = pref.getBoolean(Constant.pref_isNetworkConnected, false);
		}
		return isConnected;
	}
	
	/**
	 * 检查本地网络是否已连接,如果网络断开则提示
	 * @param context
	 * @return
	 */
	public static boolean checkNetworkConnected(Context context) {
		final Context context1 = context;
		boolean isNetworkConnected = isNetworkConnected(context);
		if(!isNetworkConnected){
        	new AlertDialog.Builder(context)
			.setTitle("设置网络")
			.setMessage("网络错误,请检查设备的网络设置或尝试重启设备。")
			.setPositiveButton("设置网络"
				, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
						context1.startActivity(intent);
					}
				}
			).setNegativeButton("取消"
				, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}
			).show();
        }
		return isNetworkConnected;
	}
}
Global site tag (gtag.js) - Google Analytics