1、Android将通信录Contacts中的数据备份到服务器
/**
* 备份到web服务器
* @param privacy
*/
public void backupData2Web(boolean privacy) {
List list = new ArrayList();//接受user对象的集合
Cursor cursor = null;
if(privacy) {
cursor = dbInstance.query(DB_TABLENAME,
new String[]{"_id","name","mobilephone","officephone","familyphone","address","othercontact","email","position","company","zipcode","remark","imageid,privacy"},
"privacy=1",
null,
null,
null,
null);
} else {
cursor = dbInstance.query(DB_TABLENAME,
new String[]{"_id","name","mobilephone","officephone","familyphone","address","othercontact","email","position","company","zipcode","remark","imageid,privacy"},
"privacy=0",
null,
null,
null,
null);
}
while(cursor.moveToNext()) {
//封装对象
User user = new User(cursor.getString(cursor.getColumnIndex("name")),
cursor.getString(cursor.getColumnIndex("mobilephone")),
cursor.getString(cursor.getColumnIndex("officephone")),
cursor.getString(cursor.getColumnIndex("familyphone")),
cursor.getString(cursor.getColumnIndex("position")),
cursor.getString(cursor.getColumnIndex("company")),
cursor.getString(cursor.getColumnIndex("address")),
cursor.getString(cursor.getColumnIndex("zipcode")),
cursor.getString(cursor.getColumnIndex("email")),
cursor.getString(cursor.getColumnIndex("othercontact")),
cursor.getString(cursor.getColumnIndex("remark")),
cursor.getInt(cursor.getColumnIndex("imageid")),
cursor.getInt(cursor.getColumnIndex("privacy")));
list.add(user);
}
//将User对象集合转换成json格式的字符串
String listJsonStr = list2json(list);
Map<String,String> params = new HashMap<String, String>();
params.put("listJsonStr", listJsonStr);
System.out.println(listJsonStr);
String path = "http://192.168.230.1:8080/contactWeb/BackupDataServlet";
try {
//sendPostRequest(path,params,"UTF-8");
sendPostRequest(path,params);
} catch (Exception e) {
e.printStackTrace();
}
//sendPOSTRequest(path,params);
//String result = HttpUtil.queryStringForPost("http://10.0.2.2:8080/contactWeb/backupDataServlet");
}
2、android发送Post请求到JavaWeb服务器端
public static boolean sendPostRequest(String path, Map<String, String> params) throws Exception{
// title=dsfdsf&timelength=23&method=save
StringBuilder sb = new StringBuilder();
if(params!=null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
sb.append(entry.getKey()).append('=')
.append(entry.getValue()).append('&');
}
sb.deleteCharAt(sb.length()-1);
}
byte[] entitydata = sb.toString().getBytes();//得到实体的二进制数据
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5 * 1000);
conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据
//Content-Type: application/x-www-form-urlencoded
//Content-Length: 38
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//必须的
conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));//必须的
OutputStream outStream = conn.getOutputStream();
outStream.write(entitydata);
outStream.flush();
outStream.close();
if(conn.getResponseCode()==200){
return true;
}
return false;
}
3、服务器端接收Json格式的字符串
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doPost");
//response.setContentType("text/html");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
/* BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while((line = br.readLine())!=null){
sb.append(line);
}
System.out.println(URLDecoder.decode(sb.toString(),"utf-8"));
*/
//解决乱码问题
String listJsonStr = new String(request.getParameter("listJsonStr").getBytes("ISO-8859-1"),"utf-8");
// [{"zipCode":"","address":"","company":"","email":"","familyPhone":"","username":"李刚","mobilePhone":"13465563223","officePhone":"","otherContact":"","position":"","remark":"","privacy":0,"imageId":2130837514,"_id":0}]
TUserDAO userDAO = new TUserDAO();
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map = null;
//数据形式:[{"id":1,"name":"小猪","age":22},{"id":2,"name":"小猫","age":23}]
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(listJsonStr);
} catch (JSONException e) {
e.printStackTrace();
}
//数据直接为一个数组形式,所以可以直接 用android提供的框架JSONArray读取JSON数据,转换成Array
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = null;
TUser user = null;
try {
item = jsonArray.getJSONObject(i);
// 获取对象对应的值
user = new TUser(item.getInt("_id"),item.getString("username"),
item.getString("mobilePhone"),
item.getString("officePhone"),
item.getString("familyPhone"),
item.getString("position"),
item.getString("company"),
item.getString("address"),
item.getString("zipCode"),
item.getString("email"),
item.getString("otherContact"),
item.getString("remark"),
item.getInt("imageId"),
item.getInt("privacy"));
userDAO.saveOrUpdate(user);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //每条记录又由几个Object对象组成
}
System.out.println(listJsonStr);
System.out.println("备份成功!");
out.flush();
out.close();
}
4、android端将java对象转换为Json字符串
/**
* List集合转换为Json
* @param list
* @return
*/
public static String list2json(List<?> list) {
StringBuilder json = new StringBuilder();
json.append("[");
if (list != null && list.size() > 0) {
for (Object obj : list) {
json.append(object2json(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
}
/**
* 对象转换为Json
* @param obj
* @return
*/
public static String object2json(Object obj) {
Gson gson = new Gson();
return gson.toJson(obj);
}