歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 使用JSON,XML向服務器端獲取資訊(獲取)

Android 使用JSON,XML向服務器端獲取資訊(獲取)

日期:2017/3/1 10:47:19   编辑:Linux編程

//只貼出,核心JSON業務類,因為Struts沒有寫。

  1. package sn.len.jandx.service;
  2. import java.io.InputStream;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import org.json.JSONArray;
  8. import org.json.JSONObject;
  9. import sn.len.jandx.domain.TestBean;
  10. import sn.len.jandx.tool.CaseInputStream;
  11. public class VideoService
  12. {
  13. public static List<TestBean> getVideo() throws Exception
  14. {
  15. //向服務器端拿取數據
  16. URL url=new URL("http://xxxx.com?format=json");
  17. HttpURLConnection conn=(HttpURLConnection)url.openConnection();
  18. conn.setConnectTimeout(5*1000);
  19. conn.setRequestMethod("GET");
  20. InputStream inStream=conn.getInputStream();
  21. byte bytedata[]=CaseInputStream.getByte(inStream);//把流轉換成byte
  22. String StringData=new String(bytedata);
  23. //一,JSON解析,前提是:服務器端發送JSON數據格式的東西,就用JSON來解析
  24. List<TestBean> listbean=VideoService.GetJson(StringData);
  25. return listbean;
  26. //二,采用XML來解析得到服務器端的數據,就像解析平常解析XML數據一樣,前提是服務器端發送XML數據
  27. }
  28. public static List<TestBean> GetJson(String jsondata) throws Exception //JSON解析方式
  29. {
  30. //JSON數據格式 [{id:1,name:"admin",longtime:40},{id:1,name:"admin",longtime:40}]
  31. List<TestBean> listBean=new ArrayList<TestBean>();
  32. //先把jsondata這個字符串轉換成一個數組
  33. JSONArray jsonarray=new JSONArray(jsondata);
  34. for(int i=0;i<jsonarray.length();i++)
  35. {
  36. //再把數組的第i項轉換成一個json對象。
  37. JSONObject jsonobj=new JSONObject();
  38. //重json對象裡面取值
  39. int id=jsonobj.getInt("id");
  40. String name=jsonobj.getString("name");
  41. int time=jsonobj.getInt("longtime");
  42. //把取到的值添加對bean中,並且把bean對象給保存起來
  43. TestBean testbean=new TestBean(id,name,time);
  44. listBean.add(testbean);
  45. //給test重新賦值一下
  46. testbean=null;
  47. }
  48. return listBean;
  49. }
  50. public static List<TestBean> getXml() //XML解析
  51. {
  52. //利用PULL解析
  53. return null;
  54. }
  55. }
//把流轉換成byte類
  1. package sn.len.jandx.tool;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. public class CaseInputStream
  6. {
  7. public static byte[] getByte(InputStream inStream) throws IOException
  8. {
  9. byte b[]=new byte[1024];
  10. int n=0;
  11. ByteArrayOutputStream byteOutPut=new ByteArrayOutputStream();
  12. while((n=inStream.read(b))!=-1)
  13. {
  14. byteOutPut.write(b);
  15. }
  16. return byteOutPut.toByteArray();
  17. }
  18. }
Copyright © Linux教程網 All Rights Reserved