Android Network Programming to get the Json on the network

Source: Internet
Author: User

Android Network Programming to get the Json on the network

Android Network Programming to get the Json on the network


Please respect others' labor achievements, and repost the Source: Android Network Programming to get the Json on the network

Server-side support is required to obtain Json on the network.

1. Create a server:

Server project structure:


Server run:


Step 1: Create the JavaBean required by the business

Package com. jph. sj. model; import java. util. date;/**** News entity class * @ author jph * Date: 2014.09.26 */public class News {private Integer 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 2: create business logic interfaces and specific implementation classes

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
 
  
GetLastNews ();}
 

Business interface implementation class:

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
 
  
GetLastNews () {List
  
   
Newes = new ArrayList
   
    
(); 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 3: 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;/*** responds to client requests: http: // xxx/NewsListServlet */public class NewsListServlet extends HttpServlet {private static final long serialVersionUID = 1L; private NewsService newsService = new NewsServiceBean (); protected void doGet (HttpServletRequest request, response) throws handle, IOException {doPost (request, response);} protected void doPost (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {List
 
  
Newes = newsService. getLastNews (); // get the latest video information // [{id: 20, title: "xxx", timelength: 90}, {id: 10, title: "xbx", timelength: 20}] StringBuilder sbJson = new StringBuilder (); // encapsulate the list set into a Json 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 (sbJson) at the end of the string. append (']'); request. setAttribute ("json", sbJson. toString (); request. getRequestDispatcher ("/WEB-INF/page/jsonnewslist. jsp "). forward (request, response );}}
 

Step 4: Create the jsonnewslist. jsp page

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

So far, the server project has been completed. Create an Android project.

2. Create an Android client:

Android project structure:


Step 1: Create the JavaBean required by the business

Tip: because both the server side and Android side projects are implemented in Java, some components can be shared, and JavaBean is one of them. At this time, we can use the JavaBean in the server project when building an Android project.

Step 2: Create the business logic layer of the Android 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 the Json on the Network * @ author jph * Date: 2014.09.26 */public class GetAndParseJson {private String url = "http: // 10.219.61.117: 8080/ServerForJSON/NewsListServlet "; public static final int PARSESUCCWSS = 0x2001; private Handler handler; public GetAndParseJson (Handler handler) {// TODO Auto-generated constructor stubthis. handler = handler;}/*** get XML on the Network */public void getJsonFromInternet () {new Thread (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubtry {HttpURLConnection conn = (HttpURLConnection) new URL (url ). openConnection (); conn. setConnectTimeout (5000); conn. setRequestMethod ("GET"); if (conn. getResponseCode () = 200) {InputStream inputStream = conn. getInputStream (); List
 
  
ListNews = parseJson (inputStream); if (listNews. size ()> 0) {Message msg = new Message (); msg. what = PARSESUCCWSS; // notifies the UI thread of Json parsing completion msg. obj = listNews; // transmits the parsed data to the UI thread handler. sendMessage (msg) ;}} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}). start ();}/*** parses the input stream in json format and converts it to List * @ param inputStream * @ return List */protected List
  
   
ParseJson (InputStream inputStream) {// TODO Auto-generated method stubList
   
    
ListNews = new ArrayList
    
     
(); 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 (time); listNews. add (news );}} Catch (JSONException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return listNews;}/*** convert the input to ByteArray * @ param inputStream * @ return ByteArray */private byte [] convertIsToByteArray (InputStream inputStream) {// 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 3: Create an 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 the Json on the Network * @ author jph * Date: 2014.09.26 */public class MainActivity extends Activity {private List
 
  
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
  
   
) Msg. obj; initData (); break;} 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 ();}/*** fill the parsed xml into ListView */protected void initData () {// TODO Auto-generated method stubList
   
    
> Items = new ArrayList
    
     
> (); For (News news: listNews) {Map
     
      
Item = new HashMap
      
        (); 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, the Android project has been completed. Let's take a look at the APP running effect:

Android running:

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.