Android network programming to get JSON on the network

Source: Internet
Author: User

Android network programming to get JSON on the network


Please respect other people's labor results, reproduced please specify the source: Android network programming to get JSON on the network

Server-side support is required to get the JSON on the network.

First, create server-side:

Server-side project structure:


Server-side operation:


First step: Create the JavaBean required for your business

Package Com.jph.sj.model;import java.util.date;/** * News entity class * @author JPH * date:2014.09.26 */public class News {Private in Teger id;private string title;private date publishdate;public News (Integer ID, String title, date publishdate) {this.id = Id;this.title = Title;this.publishdate = publishdate;} 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 Date Getpublishdate () {return publishdate;} public void Setpublishdate (Date publishdate) {this.publishdate = Publishdate;}}

Step Two: Create a business logic interface and a concrete implementation class

Business interface:

Package Com.jph.sj.service;import Java.util.list;import Com.jph.sj.model.news;public interface Newsservice {/** * Get the latest information * @return */public list<news> getlastnews ();}

Implementation class for the business interface:

Package Com.jph.sj.service.impl;import Java.util.arraylist;import Java.util.date;import java.util.List;import Com.jph.sj.model.news;import Com.jph.sj.service.newsservice;public class Newsservicebean implements NewsService {/** * Get the latest video information * @return */public list<news> getlastnews () {list<news> Newes = new arraylist<news> (); Newes . Add (New News (1, "Li Bai", New Date (System.currenttimemillis ())), Newes.add (New News (2, "Du Fu", new Date ( System.currenttimemillis () (+8200))); Newes.add (New News (3, "Jia Baoyu", New Date (System.currenttimemillis () -6000)); return Newes;}}

Step Three: Create a controller servlet

Package Com.jph.sj.servlet;import Java.io.ioexception;import Java.util.list;import javax.servlet.ServletException; Import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.jph.sj.model.news;import Com.jph.sj.service.newsservice;import com.jph.sj.service.impl.newsservicebean;/** * is responsible for responding to client requests: Http://xxx/NewsListServlet/NewsListServlet */public class  Newslistservlet extends HttpServlet {private static final long Serialversionuid = 1l;private Newsservice newsservice = new Newsservicebean ();p rotected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doPost (request, response);} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { List<news> Newes = Newsservice.getlastnews ();//Get the latest video information//[{id:20,title: "XXX", Timelength:90},{id:10,title: " Xbx ", Timelength:20}]stringbuilder Sbjson = new StrinGbuilder ();//encapsulates the list collection into a JSON-formatted string sbjson.append (' ['); for (News News:newes) {sbjson.append (' {'); Sbjson.append ("ID:" ). Append (News.getid ()). Append (","); Sbjson.append ("Title:\"). Append (News.gettitle ()). Append ("\", "); Sbjson.append ("Publishdate:"). Append (News.getpublishdate (). GetTime ()); Sbjson.append ("},");} Sbjson.deletecharat (Sbjson.length ()-1);//delete the comma at the end of the string Sbjson.append ('] '); Request.setattribute ("JSON", Sbjson.tostring ()); Request.getrequestdispatcher ("/web-inf/page/jsonnewslist.jsp"). Forward (request, response);}}

Fourth Step: Create jsonnewslist.jsp page

<%@ page language= "java" contenttype= "Text/plain; Charset=utf-8 "pageencoding=" UTF-8 "%>${json}

The server-side project has been completed. Start creating an Android -side project below.

Second, create the Android side:

Android End Project Structure:


First step: Create the JavaBean required for your business

Tips: because server-side and Android end projects are all using the Java language implementation, so some components can be shared, JavaBean is one of them. When we build the Android Project, we can fully use the JavaBean in the server-side project .

Step Two: Create the business logic layer of the Android-side project

Core code: Getandparsejson:

Package Com.jph.gj.service;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;import Java.util.ArrayList;import Java.util.date;import Java.util.list;import Org.json.jsonarray;import Org.json.jsonexception;import Org.json.jsonobject;import com.jph.model.news;import Android.os.handler;import android.os.Message;/** * Get and parse JSON on the network * @author JPH * date:2014.09.26 */public class Getandparsejson {private String url= "http://10.219.61.117:80 80/serverforjson/newslistservlet ";p ublic static final int parsesuccwss=0x2001;private Handler handler;public Getandparsejson (Handler Handler) {//TODO auto-generated constructor Stubthis.handler=handler;} /** * Get xml */public void Getjsonfrominternet () {New Thread (new Runnable () {@Overridepublic void Run () {//TODO auto-on the network Generated method Stubtry {httpurlconnection conn= (httpurlconnection) new URL (URL). OpenConnection (); Conn.setconnecttimeout (conn.setrequest);Method ("GET"), if (Conn.getresponsecode () ==200) {InputStream inputstream=conn.getinputstream (); List<news>listnews=parsejson (InputStream); if (Listnews.size () >0) {message msg=new message (); msg.what= parsesuccwss;//notifies the UI thread that the JSON parsing is complete msg.obj=listnews;//passes the parsed data to the UI thread Handler.sendmessage (msg);}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}). Start ();} /** * Parse the input stream in JSON format for list * @param inputstream * @return list */protected list<news> Parsejson (InputStream inputstre AM) {//TODO auto-generated method Stublist<news>listnews=new arraylist<news> (); byte[]jsonbytes= Convertistobytearray (InputStream); String Json=new string (jsonbytes), try {jsonarray jsonarray=new Jsonarray (JSON), for (int i = 0; i < jsonarray.length (); i++) {Jsonobject jobject=jsonarray.getjsonobject (i); int id=jobject.getint ("id"); String title=jobject.getstring ("title"); Long Time=jobject.getlong ("publishdate"); News News=new News (ID, title, new Date); Listnews.add (News);}}catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return listnews;} /** * Convert input stream to ByteArray * @param inputstream * @return ByteArray */private byte[] Convertistobytearray (InputStream inputstr EAM) {//TODO auto-generated method Stubbytearrayoutputstream baos=new bytearrayoutputstream (); byte buffer[]=new byte[ 1024];int Length=0;try {while ((Length=inputstream.read (buffer))!=-1) {baos.write (buffer, 0, length);} Inputstream.close (); Baos.flush ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} return Baos.tobytearray ();}}

Step Three: Create Activity

Package Com.jph.gj.activity;import Java.text.simpledateformat;import Java.util.arraylist;import java.util.Date; Import Java.util.hashmap;import java.util.list;import Java.util.map;import Com.jph.gj.r;import Com.jph.gj.service.getandparsejson;import Com.jph.model.news;import Android.os.bundle;import Android.os.Handler; Import Android.os.message;import Android.app.activity;import Android.widget.listview;import  android.widget.simpleadapter;/** * Get JSON on the network * @author JPH * date:2014.09.26 */public class Mainactivity extends Activity {private List<news>listnews;private ListView List; Handler mhandler=new Handler () {@Overridepublic void Handlemessage (Message msg) {//TODO auto-generated method Stubswitch (msg.what) {case getandparsejson.parsesuccwss:listnews= (list<news>) msg.obj;initdata (); Super.handlemessage (msg);}}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); list= (ListView) Findviewbyid(r.id.list); Getandparsejson getandparsejson=new Getandparsejson (Mhandler); Getandparsejson.getjsonfrominternet ();} /** * Populates the parsed XML into the ListView */protected void InitData () {//TODO auto-generated method Stublist<map<string, Object&gt ; >items=new arraylist<map<string,object>> (); for (News news:listnews) {map<string, Object>item= New hashmap<string, object> (), Item.put ("id", News.getid ()), Item.put ("title", News.gettitle ()), Item.put ("Time ", Convertdate (News.getpublishdate ())); Items.Add (item);} Simpleadapter adapter=new Simpleadapter (this, items, r.layout.line, new string[]{"id", "title", "Time"}, new int[]{ R.id.tvid,r.id.tvtitle,r.id.tvtime}); List.setadapter (adapter);} Private String convertdate (Date publishdate) {//TODO auto-generated method Stubsimpledateformat sdf=new SimpleDateFormat ("Yyyy-mm-dd hh-mm-ss"); return Sdf.format (Publishdate);}}

so far Android the end project has been completed. Let's look at how the APP works:

Android Run:

Android network programming to get JSON on the network

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.