android客戶端從服務器端獲取json數據並解析


今天總結一下:

首先客戶端從服務器端獲取json數據

1、利用HttpUrlConnection

 1 /**
 2      * 從指定的URL中獲取數組
 3      * @param urlPath
 4      * @return
 5      * @throws Exception
 6      */
 7     public static String readParse(String urlPath) throws Exception {  
 8                ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
 9                byte[] data = new byte[1024];  
10                 int len = 0;  
11                 URL url = new URL(urlPath);  
12                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
13                 InputStream inStream = conn.getInputStream();  
14                 while ((len = inStream.read(data)) != -1) {  
15                     outStream.write(data, 0, len);  
16                 }  
17                 inStream.close();  
18                 return new String(outStream.toByteArray());//通過out.Stream.toByteArray獲取到寫的數據  
19             }  

2、利用HttpClient

 1 /**
 2      * 訪問數據庫並返回JSON數據字符串
 3      * 
 4      * @param params 向服務器端傳的參數
 5      * @param url
 6      * @return
 7      * @throws Exception
 8      */
 9     public static String doPost(List<NameValuePair> params, String url)
10             throws Exception {
11         String result = null;
12         // 獲取HttpClient對象
13         HttpClient httpClient = new DefaultHttpClient();
14         // 新建HttpPost對象
15         HttpPost httpPost = new HttpPost(url);
16         if (params != null) {
17             // 設置字符集
18             HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
19             // 設置參數實體
20             httpPost.setEntity(entity);
21         }
22 
23         /*// 連接超時
24         httpClient.getParams().setParameter(
25                 CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
26         // 請求超時
27         httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
28                 3000);*/
29         // 獲取HttpResponse實例
30         HttpResponse httpResp = httpClient.execute(httpPost);
31         // 判斷是夠請求成功
32         if (httpResp.getStatusLine().getStatusCode() == 200) {
33             // 獲取返回的數據
34             result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
35         } else {
36             Log.i("HttpPost", "HttpPost方式請求失敗");
37         }
38 
39         return result;
40     }

其次Json數據解析:
json數據:[{"id":"67","biaoTi":"G","logo":"http://www.nuoter.com/wtserver/resources/upload/13508741845270.png","logoLunbo":"http://www.nuoter.com/wtserver/resources/upload/13509015004480.jpg","yuanJia":"0","xianJia":"0"},{"id":"64","biaoTi":"444","logo":"http://www.nuoter.com/wtserver/resources/upload/13508741704400.png","logoLunbo":"http://172.16.1.75:8080/wtserver/resources/upload/13508741738500.png","yuanJia":"0","xianJia":"0"},{"id":"62","biaoTi":"jhadasd","logo":"http://www.nuoter.com/wtserver/resources/upload/13508741500450.png","logoLunbo":"http://172.16.1.75:8080/wtserver/resources/upload/13508741557450.png","yuanJia":"1","xianJia":"0"}]

 

 1 /**
 2      * 解析
 3      * 
 4      * @throws JSONException
 5      */
 6     private static ArrayList<HashMap<String, Object>> Analysis(String jsonStr)
 7             throws JSONException {
 8         /******************* 解析 ***********************/
 9         JSONArray jsonArray = null;
10         // 初始化list數組對象
11         ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
12         jsonArray = new JSONArray(jsonStr);
13         for (int i = 0; i < jsonArray.length(); i++) {
14             JSONObject jsonObject = jsonArray.getJSONObject(i);
15             // 初始化map數組對象
16             HashMap<String, Object> map = new HashMap<String, Object>();
17             map.put("logo", jsonObject.getString("logo"));
18             map.put("logoLunbo", jsonObject.getString("logoLunbo"));
19             map.put("biaoTi", jsonObject.getString("biaoTi"));
20             map.put("yuanJia", jsonObject.getString("yuanJia"));
21             map.put("xianJia", jsonObject.getString("xianJia"));
22             map.put("id", jsonObject.getInt("id"));
23             list.add(map);
24         }
25         return list;
26     }

 

 最后數據適配:

1、TextView

 1 /**
 2  * readParse(String)從服務器端獲取數據
 3  * Analysis(String)解析json數據
 4  */
 5     private void resultJson() {
 6         try {
 7             allData = Analysis(readParse(url));
 8             Iterator<HashMap<String, Object>> it = allData.iterator();
 9             while (it.hasNext()) {
10                 Map<String, Object> ma = it.next();
11                 if ((Integer) ma.get("id") == id) {
12                     biaoTi.setText((String) ma.get("biaoTi"));
13                     yuanJia.setText((String) ma.get("yuanJia"));
14                     xianJia.setText((String) ma.get("xianJia"));
15                 }
16             }
17         } catch (JSONException e) {
18             e.printStackTrace();
19         } catch (Exception e) {
20             e.printStackTrace();
21         }
22     }

2、ListView:

 1 /**
 2      * ListView 數據適配
 3      */
 4     private void product_data(){ 
 5         List<HashMap<String, Object>> lists = null;
 6         try {
 7             lists = Analysis(readParse(url));//解析出json數據
 8         } catch (Exception e) {
 9             // TODO Auto-generated catch block
10             e.printStackTrace();
11         }
12         List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
13         for(HashMap<String, Object> news : lists){
14             HashMap<String, Object> item = new HashMap<String, Object>();
15             item.put("chuXingTianShu", news.get("chuXingTianShu"));
16             item.put("biaoTi", news.get("biaoTi"));
17             item.put("yuanJia", news.get("yuanJia"));
18             item.put("xianJia", news.get("xianJia"));
19             item.put("id", news.get("id"));
20             
21             try {
22                 bitmap = ImageService.getImage(news.get("logo").toString());//圖片從服務器上獲取
23             } catch (Exception e) {
24                 // TODO Auto-generated catch block
25                 e.printStackTrace();
26             }
27             if(bitmap==null){
28                 Log.i("bitmap", ""+bitmap);
29                 Toast.makeText(TravelLine.this, "圖片加載錯誤", Toast.LENGTH_SHORT)
30                 .show();                                         // 顯示圖片編號
31             }
32             item.put("logo",bitmap);
33             data.add(item);
34         }
35              listItemAdapter = new MySimpleAdapter1(TravelLine.this,data,R.layout.a_travelline_item,
36                         // 動態數組與ImageItem對應的子項
37                         new String[] { "logo", "biaoTi",
38                                 "xianJia", "yuanJia", "chuXingTianShu"},
39                         // ImageItem的XML文件里面的一個ImageView,兩個TextView ID
40                         new int[] { R.id.trl_ItemImage, R.id.trl_ItemTitle,
41                                 R.id.trl_ItemContent, R.id.trl_ItemMoney,
42                                 R.id.trl_Itemtoday});
43                 listview.setAdapter(listItemAdapter);
44                 //添加點擊   
45                 listview.setOnItemClickListener(new OnItemClickListener() {    
46                     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,   
47                             long arg3) {   
48                         login_publicchannel_trl_sub(arg2);
49                     }   
50                 });
51     }

對於有圖片的要重寫適配器

 1 package com.nuoter.adapterUntil;
 2 
 3 
 4 import java.util.HashMap;
 5 import java.util.List;
 6 
 7 
 8 import android.content.Context;
 9 import android.graphics.Bitmap;
10 import android.graphics.BitmapFactory;
11 import android.graphics.Paint;
12 import android.net.Uri;
13 import android.view.LayoutInflater;
14 import android.view.View;
15 import android.view.ViewGroup;
16 import android.widget.BaseAdapter;
17 import android.widget.ImageView;
18 import android.widget.LinearLayout;
19 import android.widget.TextView;
20 
21 
22 public class MySimpleAdapter1 extends BaseAdapter {  
23     private LayoutInflater mInflater;  
24     private List<HashMap<String, Object>> list;  
25     private int layoutID;  
26     private String flag[];  
27     private int ItemIDs[];  
28     public MySimpleAdapter1(Context context, List<HashMap<String, Object>> list,  
29             int layoutID, String flag[], int ItemIDs[]) {  
30         this.mInflater = LayoutInflater.from(context);  
31         this.list = list;  
32         this.layoutID = layoutID;  
33         this.flag = flag;  
34         this.ItemIDs = ItemIDs;  
35     }  
36     @Override  
37     public int getCount() {  
38         // TODO Auto-generated method stub  
39         return list.size();  
40     }  
41     @Override  
42     public Object getItem(int arg0) {  
43         // TODO Auto-generated method stub  
44         return 0;  
45     }  
46     @Override  
47     public long getItemId(int arg0) {  
48         // TODO Auto-generated method stub  
49         return 0;  
50     }  
51     @Override  
52     public View getView(int position, View convertView, ViewGroup parent) {  
53         convertView = mInflater.inflate(layoutID, null);  
54        // convertView = mInflater.inflate(layoutID, null);  
55         for (int i = 0; i < flag.length; i++) {//備注1  
56             if (convertView.findViewById(ItemIDs[i]) instanceof ImageView) {  
57                 ImageView imgView = (ImageView) convertView.findViewById(ItemIDs[i]);  
58                 imgView.setImageBitmap((Bitmap) list.get(position).get(flag[i]));///////////關鍵是這句!!!!!!!!!!!!!!!
59  
60             }else if (convertView.findViewById(ItemIDs[i]) instanceof TextView) {  
61                 TextView tv = (TextView) convertView.findViewById(ItemIDs[i]);  
62                 tv.setText((String) list.get(position).get(flag[i]));  
63             }else{
64                 //...備注2 
65             }  
66         }  
67         //addListener(convertView); 
68         return convertView;  
69     }  
70 
71 /*    public void addListener(final View convertView) {
72         
73         ImageView imgView = (ImageView)convertView.findViewById(R.id.lxs_item_image);
74         
75         
76  
77     } */
78 
79 }  

對於圖片的獲取,json解析出來的是字符串url:"logoLunbo":http://www.nuoter.com/wtserver/resources/upload/13509015004480.jpg 從url獲取 圖片

ImageService工具類

 1 package com.nuoter.adapterUntil;
 2 
 3 import java.io.ByteArrayOutputStream;
 4 import java.io.InputStream;
 5 import java.net.HttpURLConnection;
 6 import java.net.URL;
 7 
 8 import android.graphics.Bitmap;
 9 import android.graphics.BitmapFactory;
10 
11 
12 public class ImageService {
13     
14     /**
15      * 獲取網絡圖片的數據
16      * @param path 網絡圖片路徑
17      * @return
18      */
19     public static Bitmap getImage(String path) throws Exception{
20         
21         /*URL url = new URL(imageUrl);   
22         HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
23         InputStream is = conn.getInputStream();   
24         mBitmap = BitmapFactory.decodeStream(is);*/
25         Bitmap bitmap= null;
26         URL url = new URL(path);
27         HttpURLConnection conn = (HttpURLConnection) url.openConnection();//基於HTTP協議連接對象
28         conn.setConnectTimeout(5000);
29         conn.setRequestMethod("GET");
30         if(conn.getResponseCode() == 200){
31             InputStream inStream = conn.getInputStream();
32             bitmap = BitmapFactory.decodeStream(inStream);
33         }
34         return bitmap;
35     }
36     
37     /**
38      * 讀取流中的數據 從url獲取json數據
39      * @param inStream
40      * @return
41      * @throws Exception
42      */
43     public static byte[] read(InputStream inStream) throws Exception{
44         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
45         byte[] buffer = new byte[1024];
46         int len = 0;
47         while( (len = inStream.read(buffer)) != -1){
48             outStream.write(buffer, 0, len);
49         }
50         inStream.close();
51         return outStream.toByteArray();
52     }
53 
54 
55 }

上面也將從url處獲取網絡數據寫在了工具類ImageService中方面調用,因為都是一樣的。

當然也可以在Activity類中寫一個獲取服務器圖片的函數(當用處不多時)

 1  /*
 2 
 3      * 從服務器取圖片
 4      * 參數:String類型
 5      * 返回:Bitmap類型
 6 
 7      */
 8 
 9     public static Bitmap getHttpBitmap(String urlpath) {
10         Bitmap bitmap = null;
11         try {
12             //生成一個URL對象
13             URL url = new URL(urlpath);
14             //打開連接
15             HttpURLConnection conn = (HttpURLConnection)url.openConnection();
16 //            conn.setConnectTimeout(6*1000);
17 //            conn.setDoInput(true);
18             conn.connect();
19             //得到數據流
20             InputStream inputstream = conn.getInputStream();
21             bitmap = BitmapFactory.decodeStream(inputstream);
22             //關閉輸入流
23             inputstream.close();
24             //關閉連接
25             conn.disconnect();
26         } catch (Exception e) {
27             Log.i("MyTag", "error:"+e.toString());
28         }
29         return bitmap;
30     }

調用:

 1 public ImageView pic;
 2 .....
 3 .....
 4 allData=Analysis(readParse(url));
 5 Iterator<HashMap<String, Object>> it=allData.iterator();
 6 while(it.hasNext()){
 7 Map<String, Object> ma=it.next();
 8 if((Integer)ma.get("id")==id)
 9 {
10 logo=(String) ma.get("logo");
11 bigpic=getHttpBitmap(logo);
12 }
13 }
14 pic.setImageBitmap(bigpic);

另附 下載數據很慢時建立子線程並傳參:

 1 new Thread() {
 2             @Override
 3             public void run() {
 4                 // 參數列表
 5                 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
 6                 nameValuePairs.add(new BasicNameValuePair("currPage", Integer
 7                         .toString(1)));
 8                 nameValuePairs.add(new BasicNameValuePair("pageSize", Integer
 9                         .toString(5)));
10                 try {
11                     String result = doPost(nameValuePairs, POST_URL);                    
12                     Message msg = handler.obtainMessage(1, 1, 1, result);
13                     handler.sendMessage(msg);                     // 發送消息
14                 } catch (Exception e) {
15                     // TODO Auto-generated catch block
16                     e.printStackTrace();
17                 }
18             }
19         }.start();
20 
21         // 定義Handler對象
22         handler = new Handler() {
23             public void handleMessage(Message msg) {
24                 switch (msg.what) {
25                 case 1:{
26                     // 處理UI
27                     StringBuffer strbuf = new StringBuffer();
28                     List<HashMap<String, Object>> lists = null;
29                     try {
30                         lists = MainActivity.this
31                                 .parseJson(msg.obj.toString());
32                     } catch (Exception e) {
33                         // TODO Auto-generated catch block
34                         e.printStackTrace();
35                     }
36                     List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
37                     for(HashMap<String, Object> news : lists){
38                         HashMap<String, Object> item = new HashMap<String, Object>();
39                         item.put("id", news.get("id"));
40                         item.put("ItemText0", news.get("name"));
41                         
42                         try {
43                             bitmap = ImageService.getImage(news.get("logo").toString());
44                         } catch (Exception e) {
45                             // TODO Auto-generated catch block
46                             e.printStackTrace();
47                         }
48                         if(bitmap==null){
49                             Log.i("bitmap", ""+bitmap);
50                             Toast.makeText(MainActivity.this, "圖片加載錯誤", Toast.LENGTH_SHORT)
51                             .show();                                         // 顯示圖片編號
52                         }
53                         item.put("ItemImage",bitmap);
54                         data.add(item);
55                     }
56                     
57                     //生成適配器的ImageItem <====> 動態數組的元素,兩者一一對應
58                     MySimpleAdapter saImageItems = new MySimpleAdapter(MainActivity.this, data, 
59                             R.layout.d_travelagence_item, 
60                             new String[] {"ItemImage", "ItemText0", "ItemText1"}, 
61                             new int[] {R.id.lxs_item_image, R.id.lxs_item_text0, R.id.lxs_item_text1});
62                     //添加並且顯示
63                     gridview.setAdapter(saImageItems);
64                 }
65                     break;
66                 default:
67                     break;
68                 }
69                 
70                 
71             }
72         };

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM