在设备通讯中,往往会用到数据交互。我们这里用的是通过HTTP协议发送JSON数据,android客户端把数据进行打包,发送到后台服务器,后台解析出来。
//android客户端拼装JSON字符串
//如下的拼装结果为:
{"data":[{"id":"12345","name":"张三"},{"id":"54321","name":"李四"}]}JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
try {
jsonObject.put("name", "张三");
jsonObject.put("id", "12345");
jsonArray.put(jsonObject);
jsonObject = new JSONObject();
jsonObject.put("name", "李四");
jsonObject.put("id", "54321");
jsonArray.put(jsonObject);
String json = "{\"data\":"+jsonArray.toString()+"}";
Log.v("zd", "json");
result = new HttpUtils().sendJsonData(Consant.ip + Consant.url3, json);
mHandler.sendEmptyMessage(0x0001);
} catch (JSONException e) {
e.printStackTrace();
}/**
* 向服务器发送数据,编码类型为utf-8
* svrUrl为服务器地址
* ParamStr为JSON字符串
* 发送类型为 POST
*/
public String sendJsonData(String svrUrl, String ParamStr) {
Log.v("zd", "send json");
try {
// 转成指定格式
byte[] requestData = ParamStr.getBytes("UTF-8");
HttpURLConnection conn = null;
DataOutputStream outStream = null;
String MULTIPART_FORM_DATA = "multipart/form-data";
// 构造一个post请求的http头
URL url = new URL(svrUrl); // 服务器地址
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // 允许输入
conn.setDoOutput(true); // 允许输出
conn.setUseCaches(false); // 不使用caches
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA);
conn.setRequestProperty("Content-Length", Long.toString(requestData.length));
conn.setRequestProperty("data", ParamStr);
// 请求参数内容, 获取输出到网络的连接流对象
outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(requestData, 0, requestData.length);
outStream.flush();
outStream.close();
ByteArrayOutputStream outStream2 = new ByteArrayOutputStream();
int cah = conn.getResponseCode();
if (cah != 200) {
Log.v("data", "服务器响应错误代码:" + cah);
return "0";
}else if(cah == 200){
Log.v("data", "服务器响应成功:" + cah);
}
InputStream inputStream = conn.getInputStream();
int len = 0;
byte[] data = new byte[1024];
while ((len = inputStream.read(data)) != -1) {
outStream2.write(data, 0, len);
}
outStream2.close();
inputStream.close();
String responseStr = new String(outStream2.toByteArray());
Log.v("data", "data = " + responseStr);
return responseStr;
} catch (Exception e) {
return "";
}
}接下来看一看后台的处理
后台用的是Java利用Tomcat作为服务器
创建的是一个动态的Web项目,通过Servlet的doPost()方法来接收
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String method = request.getParameter("method").toString();
System.out.println("method = " + method);
System.out.println(new Date().toLocaleString());
String jsonData = getData(request);
try {
jsonStringToList(jsonData);
} catch (Exception e) {
e.printStackTrace();
}
doGet(request, response);
}public String getData(HttpServletRequest req){
String result = null;
try {
//包装request的输入流
BufferedReader br = new BufferedReader(
new InputStreamReader((ServletInputStream) req.getInputStream(), "utf-8"));
//缓冲字符
StringBuffer sb=new StringBuffer("");
String line;
while((line=br.readLine())!=null){
sb.append(line);
}
br.close();//关闭缓冲流
result=sb.toString();//转换成字符
System.out.println("result = " + result);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}通过getData()方法获取发送的字符流即JSON字符串
接下来对json字符串进行解析
首先我们来分析一下这个json字符串的特点
{"data":[{"id":"12345","name":"张三"},{"id":"54321","name":"李四"}]}
可以发现它符合这样一个类型{key : value}即JSonObject类型
通过这样的方法把它转为JSONObject
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
在这里会出现两种情况,知道key值和不知道key值。
第一种知道Key我们可以根据key值直接取value
String msg = jsonObject.getString("data").toString();取出来的结果即为:
[{"id":"12345","name":"张三"},{"id":"54321","name":"李四"}]第二种在不知道key值的情况取值,用到了迭代器
for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();) {
String key = (String) iter.next();
String value = jsonObject.get(key).toString();
System.out.println(key + "/" + value);
map.put(key, value);
}这里的key和value
分别对应data、[{"id":"12345","name":"张三"},{"id":"54321","name":"李四"}]
接下来我们再分析一下取出来的value值
不难发现它是一个JSonArray类型
我们用for循环来遍历这个jsonarray
在这里同样有两种情况,知道key值和不知道key值
知道key值直接根据key取即可,不知道则利用迭代器,至于迭代器不做详细介绍
for (int i = 0; i < jsonArray.size(); i++) {
jsonObject = jsonArray.getJSONObject(i);
Map<String, String> map = new HashMap<String, String>();
for (Iterator<?> iter = jsonObject.keys(); iter.hasNext();) {
String key = (String) iter.next();
String value = jsonObject.get(key).toString();
System.out.println(key + "/" + value);
map.put(key, value);
}
//这里是知道key值,直接取数据
//String name = jsonObject.getString("name").toString();
//String id = jsonObject.getString("id").toString();
//
//System.out.println(name + "/" + id);
}id/12345 name/张三 id/54321 name/李四
PS:我们这里传过来的JSON数据类型为JSonObject,有时也会传过来JSonArray类型
JSONArray jsonArray = JSONArray.fromObject(jsonStr);
只需转换为JsonArray即可。
本文出自 “爬过山见过海” 博客,请务必保留此出处http://670176656.blog.51cto.com/4500575/1692195
原文地址:http://670176656.blog.51cto.com/4500575/1692195