Android Development: JSON send and receive

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.