編輯:關於Android編程
Android網絡編程之獲取網絡上的Json
請尊重他人的勞動成果,轉載請注明出處:Android網絡編程之獲取網絡上的Json
為要獲取網絡上的Json所以需要服務器端提供的支持。
服務器端項目結構:
服務器端運行效果圖:
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 ListgetLastNews(); }
業務接口的實現類:
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 ListgetLastNews(){ List newes = new ArrayList (); 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; } }
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 { Listnewes = 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); } }
<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%> ${json}
至此服務器端項目已經完成。下面開始創建Android端項目。
Android端項目結構:
提示:因為服務器端和Android端項目都是用Java語言實現的,所以一些組件可以共用,JavaBean便是其中之一。此時我們在搭建Android端項目的時候,完全可以將服務器端項目中JavaBean拿來用。
核心代碼: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(); ListlistNews=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 parseJson(InputStream inputStream) { // TODO Auto-generated method stub List 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 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(); } }
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 ListlistNews; 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 ) 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
至此Android端項目已經完成了。下面就讓我們看一下APP運行效果吧:
Android運行效果圖:
在Android 5.0 中引入了Material Design的設計理念,並加入了RecyclerView和CardView兩個控件。本文就講解如何使用者兩個控件來實現
PullToRefresh 這個庫用的是非常至多,github 今天主要分析一下源碼實現.我們通過ListView的下拉刷新進行分析,其它的類似。整個下拉刷新 父View
本文實例講述了Android游戲開發學習①彈跳小球實現方法。分享給大家供大家參考。具體如下:在學習了一點點Android之後,覺得有必要記錄下來,於是就開了這個新坑,慢慢
本文實例為大家分享了Andriod滑動布局的具體代碼,供大家參考,具體內容如下MainActivity.java代碼:package siso.swipelayoutde