Recently engaged in an Android app that uses JSON interactive technology to and from the server. Server side I was simply using a servlet to receive requests from the app, processing JSON using the Org.json jar package.
Server-side:
1. The object to be sent is processed into a jsonobject or Jsonarray object so that the ToString becomes a JSON statement.
Jsonarray Jsonarr = Reader.getnewsiteminjson (page);
2. Set the content type of the response header to: Text/json
Response.setcontenttype ("Text/json;charset=utf-8");
3. Convert object to byte array, write to output stream
Response.getoutputstream (). Write (Jsonarr.tostring (). GetBytes ());
The Android app side uses the normal HTTP protocol to get the data, the code is as follows.
1 Public Staticstring readjsonstring (String urlstr) {2StringBuffer SB =NewStringBuffer ();3HttpURLConnection conn=NULL;4 Try{5URL url =NewURL (URLSTR);6conn =(HttpURLConnection) url.openconnection ();7Conn.setrequestmethod ("GET");8Conn.setconnecttimeout (5000);9Conn.setdoinput (true);Ten if(Conn.getresponsecode () ==200){ OneInputStream is =Conn.getinputstream (); ABytearrayoutputstream OutputStream =NewBytearrayoutputstream (); - byte[] buffer =New byte[1024]; - intLen=0; the while(true){ -Len =is.read (buffer); - if(Len==-1){ - Break; +}Else { - outputstream.write (buffer); + } A } at byte[] result =Outputstream.tobytearray (); -String str =NewString (result, 0, result.length, "GBK")); - sb.append (str); - outputstream.close (); - is.close (); - } in}Catch(Exception e) { - e.printstacktrace (); to}finally { + if(conn!=NULL) { - Conn.disconnect (); the } * } $ returnsb.tostring ();Panax Notoginseng}
Android Development: JSON send and receive