Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發實例 >> Android網絡編程之獲取網絡上的Json數據實例

Android網絡編程之獲取網絡上的Json數據實例

編輯:Android開發實例

為要獲取網絡上的Json所以需要服務器端提供的支持。

一、創建服務器端:

服務器端項目結構:

服務器端運行效果圖:

第一步:創建業務所需的JavaBean

代碼如下:

 package com.jph.sj.model;
 
import java.util.Date;
 
/**
 * 新聞實體類
 * @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;
    }
}

第二步:創建業務邏輯接口和具體實現類

業務接口:

代碼如下:

package com.jph.sj.service;
 
import java.util.List;
 
import com.jph.sj.model.News;
 
 
public interface NewsService {
 
    /**
     * 獲取最新的資訊
     * @return
     */
    public List<News> getLastNews();
 
}

業務接口的實現類:

代碼如下:

  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 {
    /**
     * 獲取最新的視頻資訊
     * @return
     */
    public List<News> getLastNews(){      
        List<News> newes = new ArrayList<News>();
        newes.add(new News(1, "李白", new Date(System.currentTimeMillis())));
        newes.add(new News(2, "杜甫", new Date(System.currentTimeMillis()+8200)));
        newes.add(new News(3, "賈寶玉",new Date(System.currentTimeMillis()-6000)));
        return newes;
    }
}

第三步:創建控制器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;
 
 
/**
 * 負責響應客戶端的請求:http://xxx/NewsListServlet/NewsListServlet
 */
public class NewsListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private NewsService newsService = new NewsServiceBean();
 
    protected 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();//獲取最新的視頻資訊
            //[{id:20,title:"xxx",timelength:90},{id:10,title:"xbx",timelength:20}]
            StringBuilder sbJson = new StringBuilder();
            //將list集合封裝成Json格式的字符串
            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);//刪除字符串末尾的逗號
            sbJson.append(']');
            request.setAttribute("json", sbJson.toString());
            request.getRequestDispatcher("/WEB-INF/page/jsonnewslist.jsp").forward(request, response);
    }
}

第四步:創建jsonnewslist.jsp頁面

代碼如下:

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

至此服務器端項目已經完成。下面開始創建Android端項目。

二、創建Android端:

Android端項目結構:

第一步:創建業務所需的JavaBean

提示:因為服務器端和Android端項目都是用Java語言實現的,所以一些組件可以共用,JavaBean便是其中之一。此時我們在搭建Android端項目的時候,完全可以將服務器端項目中JavaBean拿來用。

第二步:創建Android端項目的業務邏輯層

核心代碼: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;
 
/**
 * 獲取並解析網絡上的Json
 * @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 stub
        this.handler=handler;
    }
    /**
     * 獲取網絡上的XML
     */
    public void getJsonFromInternet () {
        new Thread(new Runnable() {       
            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    HttpURLConnection conn=(HttpURLConnection) new URL(url).openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("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;//通知UI線程Json解析完成
                            msg.obj=listNews;//將解析出的數據傳遞給UI線程
                            handler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }             
            }
        }).start();
        
    }
    /**
     * 解析json格式的輸入流轉換成List
     * @param inputStream
     * @return List
     */
    protected List<News> parseJson(InputStream inputStream) {
        // TODO Auto-generated method stub
        List<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(time));
                listNews.add(news);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return listNews;
    }
    /**
     * 將輸入流轉化成ByteArray
     * @param inputStream
     * @return ByteArray
     */
    private byte[] convertIsToByteArray(InputStream inputStream) {
        // TODO Auto-generated method stub    
        ByteArrayOutputStream 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 block
            e.printStackTrace();
        }
        return baos.toByteArray();
    }
}

第三步:創建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;
 
/**
 * 獲取網絡上的Json
 * @author jph
 * Date:2014.09.26
 */
public class MainActivity extends Activity {
    private List<News>listNews;
    private ListView list;
    Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
            case GetAndParseJson.PARSESUCCWSS:
                listNews=(List<News>) msg.obj;
                initData();
                break;        
            }
            super.handleMessage(msg);
        }     
    };
    @Override
    protected 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();
    }
    /**
     * 將解析後的xml填充到ListView
     */
    protected void initData() {
        // TODO Auto-generated method stub
        List<Map<String, Object>>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 stub
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");     
        return sdf.format(publishDate);
    }
}

至此Android端項目已經完成了。下面就讓我們看一下APP運行效果吧:
Android運行效果圖:

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved