android网络通讯数据封装之 json

来源:互联网 发布:java中方法的概念 编辑:程序博客网 时间:2024/06/05 18:33
原文地址:android网络通讯数据封装之 json作者:yihu
Demo程序包括客户端和服务端
客户端按json数据格式封装数据传至服务端。
服务端为简单的servlet程序,负责接收客户端传到json数据,然后按原数据返回客户端.

实例代码如下:


</pre><pre name="code" class="html">public static String cmdLogIn() {   String urlString = "http://192.168.8.75:89/webroot/jsontest";   HttpPost request = new HttpPost(urlString);      try{    //json数据格式{"data":{"spring":"yes","java":"ok"},                   "head": {"password":"123456","name":"rarnu"}}    //封装代码         JSONObject headParam = new JSONObject();         headParam.put("name", "yihu");         headParam.put("password", "123456");         JSONObject dataParam = new JSONObject();         dataParam.put("java", "ok");         dataParam.put("spring", "yes");            JSONObject paramss = new JSONObject();         paramss.put("head", headParam);         paramss.put("data", dataParam);    //json数据格式{"data":[{"spring":"yes","java":"ok"}], "head":[{"password":"123456","name":"yihu"},{"arry1":"java","classid":"321546"}]}      JSONArray headParams = new JSONArray();   //数组[0]   JSONObject headParam1 = new JSONObject();   headParam1.put("name", "yihu");   headParam1.put("password", "123456");   //数组[1]   JSONObject headParam2 = new JSONObject();   headParam2.put("arry1", "java");   headParam2.put("classid", "321546");   headParams.put(headParam1);   headParams.put(headParam2);      JSONArray dataParams = new JSONArray();   JSONObject dataParam = new JSONObject();   dataParam.put("java", "ok");   dataParam.put("spring", "yes");   dataParams.put(dataParam);      JSONObject paramss = new JSONObject();   paramss.put("head", headParams);   paramss.put("data", dataParams);                   Log.v("tag", "params.toString() >>> :"+paramss.toString());       // 绑定到请求 Entry       StringEntity se = new StringEntity(paramss.toString());       request.setEntity(se);       // 发送请求       HttpResponse httpResponse = new DefaultHttpClient().execute(request);       int statusCode = httpResponse.getStatusLine().getStatusCode();       Log.v("tag", "statusCode <- :"+statusCode);      if (statusCode == 200) {        InputStream entityStream;        try {           entityStream = httpResponse.getEntity().getContent();           String jsonString = convertStreamToString(entityStream);           Log.v("tag", "jsonString <- :"+jsonString);           if ("".equals(jsonString))              return null;           JSONObject json = new JSONObject(jsonString);           JSONObject head = json.getJSONObject("head");           Log.v("TAG", "name >> :"+head.optString("name"));           return json.optString("java");         }catch (Exception e) {      }    }   }catch (Exception e) {   }  return null; }  private static String convertStreamToString(InputStream is) {   StringBuilder sb = new StringBuilder();   try {     BufferedReader reader = new BufferedReader(new InputStreamReader(      is, "UTF-8"), 8 * 1024);    String line = null;    while ((line = reader.readLine()) != null) {     sb.append(line + "n");    }   } catch (IOException e) {    sb.delete(0, sb.length());   } finally {    try {     is.close();    } catch (IOException e) {         }   }   return sb.toString();    }

服务端测试代码

public class LoadServlet extends HttpServlet { public void destroy() {  super.destroy(); }  public void doGet(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  StringBuffer messagebuffer = new StringBuffer();  javax.servlet.ServletInputStream in = request.getInputStream();  DataInputStream din = new DataInputStream(in);  int ch;  while ((ch = din.read()) != -1)   messagebuffer.append((char) ch);  din.close();    String message = messagebuffer.toString();  System.out.println("content...>>>:" + message);    ByteArrayOutputStream bout = new ByteArrayOutputStream();  DataOutputStream dout = new DataOutputStream(bout);  byte str[] = message.getBytes("UTF-8");  dout.write(str);  byte data[] = bout.toByteArray();  OutputStream out = response.getOutputStream();  out.write(data);  out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  doGet(request, response); } public void init() throws ServletException { }}web.xml<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  <servlet>    <description>jsontest</description>    <display-name>jsontest</display-name>       <servlet-name>jsonServlet</servlet-name>    <servlet-class>com.yihu.json.servlet.LoadServlet</servlet-class>     </servlet>  <servlet-mapping>    <servlet-name>jsonServlet</servlet-name>    <url-pattern>/jsontest</url-pattern>  </servlet-mapping></web-app>


0 0