Communication between Android and server in JSON format

Source: Internet
Author: User

Communication between Android and server in JSON format
Network Communication Json version
After adding a parameter to the path, return Json format data to the Android app.
Http: // 192.168.1.100: 8080/videonews/ListServlet? Format = json
If no parameter is added, xml format data is returned by default.
Public class VideoNewsService
{
/* Obtain server information */
Public static List GetJSONLastNews () throws Exception {
String path = "http: // 192.168.1.100: 8080/videonews/ListServlet? Format = json ";
URL url = new URL (path );
HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
Conn. setConnectionTimeout (5000 );
Conn. setRequestMethod ("GET ");
If (conn. getResponseCode () = 200)
{
InputStream inStream = conn. getInputStream ();
Return parseJSON (inStream );


}
Return null;
}
/* Parse the JSON data returned by the server */
Private static List ParseXML (InputStream inStream)
{
List Newses = new ArrayList ();
Byte [] data = StreamTool. read (inStream );
String json = new String (data );
JSONArray array = new JSONArray (json );
For (int I = 0; I {
// Obtain the Json object
JSONObject jsonObject = array. getJSONObject (I );
News news = new News (jsonObject. getInt ("id"), jsonObject. getString ("title"), jsonObject. getInt ("timelength "));
Newses. add (news );
}
Return newses;

}



Main. xml
Android: layout_width = "fill_parent ";
Android: layout_height = "wrap_content"
Android: id = "@ + id/listView"
/>
Item. xml
Android: id = "@ + id/title"
>
Android: id = "@ + id/timelength"
>





Android mainActivity:
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
ListView listview = (ListView) this. findViewById (R. id. listview );
List Videos = VideoNewsService. getJSONLastNews ();
List > Data = new ArrayList > ();
For (News news: videos)
{
HashMap Item = new HashMap ();
Item. put ("id", news. getId ());
Item. put ("title", news. getTitle ());
Item. put ("timelength", news. getTimelength ());
Data. add (item );
}
SimpleAdapter adapter = new SimpleAdapter (this, data, R. layout. item, new String [] {"title", "timelength"}, new int [] {R. id. title, R. id. timelength });
ListView. setAdapter (adapter );


Server
Web technology
1. Create a servlet
Json format
[{Id: 56, title: "XXX", timelength: 90}, {id: 16, title: "XXb", timelength: 30}]
Public class ListServlet extends HttpServlet
{
Private static final long serialVersionUID = 1L;
Private VideoNewsService service = new VideoNewsServiceBean ();
Protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
List Videos = service. getLastNews ();
String format = request. getParameter ("format ");
If ("json". equals (format ))
{
StringBuilder builder = new StringBuilder ();
Builder. append ('[');
For (News news: videos)
{
Builder. append ('{');
Builder. append ("id:"). append (news. getId (). append (',');
Builder. append ("title: \" "). append (news. getTitle (). append (" \ ","); // backslash escape
Builder. append ("timelength:"). append (news. getTimelength ());
Builder. append ("},");
}
Builder. deleteChatAt (builder. length ()-1 );
Builder. append (']');
Request. setAttribute ("json", builder. toString ());
Request. getRequestDispather ("/WEB-INF/page/jsonvideonews. jsp"). forward (request, response );
} Else
{
Request. setAttribute ("videos", videos );
Request. getRequestDispather ("/WEB-INF/page/videonews. jsp"). forward (request, response );
}
}
News class
Public class News
{
Private Integer id;
Private String title;
Private Integer timelength;
Public News (){}
Public News (Integer id, String title, Integer timelength)
{
This. id = id;
This. title = title;
This. timelength = timelength;
}
Public Integer getId ()
{
Return id;
}
Public void setId (Integer id)
{
This. id = id;
}
Public String getTitle ()
{
Return title;
}
Public void setTitle (String title)
{
This. title = title;
}
Public Integer getTimelength ()
{
Return timelength;
}
Public void setTimelength (Integer timelength)
{
This. timelength = timelength;
}
}
VideoNewsServiceBean // implementation class
Public class VideoNewsServiceBean implements VideoNewsService
{
Public List GetLastNews ()
{
List Newses = new ArrayList ();
Newses. add (new News (35, "Xi Yang", 90 ));
Newses. add (new News (12, "grey Wolf", 30 ));
Newses. add (new News (56, "Red Wolf", 40 ));
Return newses;
}
}
Public interface VideoNewsService
{
/* Obtain video information */
Public List GetLastNews ();
}

Jsonvideonews. jsp
<% @ Page language = "java" contentType = "text/plain; charset = UTF-8" pageEncoding = "UTF-8" % >$ {json}

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.