android客戶端從伺服器端獲取json數據並解析的實現代碼

来源:http://www.cnblogs.com/Onexway/archive/2016/09/07/5848538.html
-Advertisement-
Play Games

今天總結一下android客戶端從伺服器端獲取json數據的實現代碼,需要的朋友可以參考下 首先客戶端從伺服器端獲取json數據 1、利用HttpUrlConnection /** * 從指定的URL中獲取數組 * @param urlPath * @return * @throws Excepti ...


今天總結一下android客戶端從伺服器端獲取json數據的實現代碼,需要的朋友可以參考下  

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

1、利用HttpUrlConnection

/**
      * 從指定的URL中獲取數組
      * @param urlPath
      * @return
      * @throws Exception
      */
     public static String readParse(String urlPath) throws Exception {  
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
                byte[] data = new byte[1024];  
                 int len = 0;  
                 URL url = new URL(urlPath);  
                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
                 InputStream inStream = conn.getInputStream();  
                 while ((len = inStream.read(data)) != -1) {  
                     outStream.write(data, 0, len);  
                 }  
                 inStream.close();  
                 return new String(outStream.toByteArray());//通過out.Stream.toByteArray獲取到寫的數據  
             }

2、利用HttpClient

/**
      * 訪問資料庫並返回JSON數據字元串
      * 
      * @param params 向伺服器端傳的參數
      * @param url
      * @return
      * @throws Exception
      */
     public static String doPost(List<NameValuePair> params, String url)
             throws Exception {
         String result = null;
         // 獲取HttpClient對象
         HttpClient httpClient = new DefaultHttpClient();
         // 新建HttpPost對象
         HttpPost httpPost = new HttpPost(url);
         if (params != null) {
             // 設置字元集
             HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
             // 設置參數實體
             httpPost.setEntity(entity);
         }

         /*// 連接超時
         httpClient.getParams().setParameter(
                 CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
         // 請求超時
         httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                 3000);*/
         // 獲取HttpResponse實例
         HttpResponse httpResp = httpClient.execute(httpPost);
         // 判斷是夠請求成功
         if (httpResp.getStatusLine().getStatusCode() == 200) {
             // 獲取返回的數據
             result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
         } else {
             Log.i("HttpPost", "HttpPost方式請求失敗");
         }

         return result;
     }

其次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"}]

/**
      * 解析
      * 
      * @throws JSONException
      */
     private static ArrayList<HashMap<String, Object>> Analysis(String jsonStr)
             throws JSONException {
         /******************* 解析 ***********************/
         JSONArray jsonArray = null;
         // 初始化list數組對象
         ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
         jsonArray = new JSONArray(jsonStr);
         for (int i = 0; i < jsonArray.length(); i++) {
             JSONObject jsonObject = jsonArray.getJSONObject(i);
             // 初始化map數組對象
             HashMap<String, Object> map = new HashMap<String, Object>();
             map.put("logo", jsonObject.getString("logo"));
             map.put("logoLunbo", jsonObject.getString("logoLunbo"));
             map.put("biaoTi", jsonObject.getString("biaoTi"));
             map.put("yuanJia", jsonObject.getString("yuanJia"));
             map.put("xianJia", jsonObject.getString("xianJia"));
             map.put("id", jsonObject.getInt("id"));
             list.add(map);
         }
         return list;
     }

最後數據適配:

1、TextView

/**
  * readParse(String)從伺服器端獲取數據
  * Analysis(String)解析json數據
  */
     private void resultJson() {
         try {
             allData = Analysis(readParse(url));
             Iterator<HashMap<String, Object>> it = allData.iterator();
             while (it.hasNext()) {
                 Map<String, Object> ma = it.next();
                 if ((Integer) ma.get("id") == id) {
                     biaoTi.setText((String) ma.get("biaoTi"));
                     yuanJia.setText((String) ma.get("yuanJia"));
                     xianJia.setText((String) ma.get("xianJia"));
                 }
             }
         } catch (JSONException e) {
             e.printStackTrace();
         } catch (Exception e) {
             e.printStackTrace();
         }
     }

2、ListView:

/**
      * ListView 數據適配
      */
     private void product_data(){ 
         List<HashMap<String, Object>> lists = null;
         try {
             lists = Analysis(readParse(url));//解析出json數據
         } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
         for(HashMap<String, Object> news : lists){
             HashMap<String, Object> item = new HashMap<String, Object>();
             item.put("chuXingTianShu", news.get("chuXingTianShu"));
             item.put("biaoTi", news.get("biaoTi"));
             item.put("yuanJia", news.get("yuanJia"));
             item.put("xianJia", news.get("xianJia"));
             item.put("id", news.get("id"));

             try {
                 bitmap = ImageService.getImage(news.get("logo").toString());//圖片從伺服器上獲取
             } catch (Exception e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
             if(bitmap==null){
                 Log.i("bitmap", ""+bitmap);
                 Toast.makeText(TravelLine.this, "圖片載入錯誤", Toast.LENGTH_SHORT)
                 .show();                                         // 顯示圖片編號
             }
             item.put("logo",bitmap);
             data.add(item);
         }
              listItemAdapter = new MySimpleAdapter1(TravelLine.this,data,R.layout.a_travelline_item,
                         // 動態數組與ImageItem對應的子項
                         new String[] { "logo", "biaoTi",
                                 "xianJia", "yuanJia", "chuXingTianShu"},
                         // ImageItem的XML文件裡面的一個ImageView,兩個TextView ID
                         new int[] { R.id.trl_ItemImage, R.id.trl_ItemTitle,
                                 R.id.trl_ItemContent, R.id.trl_ItemMoney,
                                 R.id.trl_Itemtoday});
                 listview.setAdapter(listItemAdapter);
                 //添加點擊   
                 listview.setOnItemClickListener(new OnItemClickListener() {    
                     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,   
                             long arg3) {   
                         login_publicchannel_trl_sub(arg2);
                     }   
                 });
     }

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

package com.nuoter.adapterUntil;

 
 import java.util.HashMap;
 import java.util.List;

 
 import android.content.Context;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.graphics.Paint;
 import android.net.Uri;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.BaseAdapter;
 import android.widget.ImageView;
 import android.widget.LinearLayout;
 import android.widget.TextView;

 
 public class MySimpleAdapter1 extends BaseAdapter {  
     private LayoutInflater mInflater;  
     private List<HashMap<String, Object>> list;  
     private int layoutID;  
     private String flag[];  
     private int ItemIDs[];  
     public MySimpleAdapter1(Context context, List<HashMap<String, Object>> list,  
             int layoutID, String flag[], int ItemIDs[]) {  
         this.mInflater = LayoutInflater.from(context);  
         this.list = list;  
         this.layoutID = layoutID;  
         this.flag = flag;  
         this.ItemIDs = ItemIDs;  
     }  
     @Override  
     public int getCount() {  
         // TODO Auto-generated method stub  
         return list.size();  
     }  
     @Override  
     public Object getItem(int arg0) {  
         // TODO Auto-generated method stub  
         return 0;  
     }  
     @Override  
     public long getItemId(int arg0) {  
         // TODO Auto-generated method stub  
         return 0;  
     }  
     @Override  
     public View getView(int position, View convertView, ViewGroup parent) {  
         convertView = mInflater.inflate(layoutID, null);  
        // convertView = mInflater.inflate(layoutID, null);  
         for (int i = 0; i < flag.length; i++) {//備註1  
             if (convertView.findViewById(ItemIDs[i]) instanceof ImageView) {  
                 ImageView imgView = (ImageView) convertView.findViewById(ItemIDs[i]);  
                 imgView.setImageBitmap((Bitmap) list.get(position).get(flag[i]));///////////關鍵是這句!!!!!!!!!!!!!!!

             }else if (convertView.findViewById(ItemIDs[i]) instanceof TextView) {  
                 TextView tv = (TextView) convertView.findViewById(ItemIDs[i]);  
                 tv.setText((String) list.get(position).get(flag[i]));  
             }else{
                 //...備註2 
             }  
         }  
         //addListener(convertView); 
         return convertView;  
     }  

 /*    public void addListener(final View convertView) {

         ImageView imgView = (ImageView)convertView.findViewById(R.id.lxs_item_image);

         

     } */

 }

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

ImageService工具類

package com.nuoter.adapterUntil;

 import java.io.ByteArrayOutputStream;
 import java.io.InputStream;
 import java.net.HttpURLConnection;
 import java.net.URL;

 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;

 
 public class ImageService {

     /**
      * 獲取網路圖片的數據
      * @param path 網路圖片路徑
      * @return
      */
     public static Bitmap getImage(String path) throws Exception{

         /*URL url = new URL(imageUrl);   
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
         InputStream is = conn.getInputStream();   
         mBitmap = BitmapFactory.decodeStream(is);*/
         Bitmap bitmap= null;
         URL url = new URL(path);
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();//基於HTTP協議連接對象
         conn.setConnectTimeout(5000);
         conn.setRequestMethod("GET");
         if(conn.getResponseCode() == 200){
             InputStream inStream = conn.getInputStream();
             bitmap = BitmapFactory.decodeStream(inStream);
         }
         return bitmap;
     }

     /**
      * 讀取流中的數據 從url獲取json數據
      * @param inStream
      * @return
      * @throws Exception
      */
     public static byte[] read(InputStream inStream) throws Exception{
         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
         byte[] buffer = new byte[1024];
         int len = 0;
         while( (len = inStream.read(buffer)) != -1){
             outStream.write(buffer, 0, len);
         }
         inStream.close();
         return outStream.toByteArray();
     }
  }

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

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

/*

      * 從伺服器取圖片
      * 參數:String類型
      * 返回:Bitmap類型

      */

     public static Bitmap getHttpBitmap(String urlpath) {
         Bitmap bitmap = null;
         try {
             //生成一個URL對象
             URL url = new URL(urlpath);
             //打開連接
             HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 //            conn.setConnectTimeout(6*1000);
 //            conn.setDoInput(true);
             conn.connect();
             //得到數據流
             InputStream inputstream = conn.getInputStream();
             bitmap = BitmapFactory.decodeStream(inputstream);
             //關閉輸入流
             inputstream.close();
             //關閉連接
             conn.disconnect();
         } catch (Exception e) {
             Log.i("MyTag", "error:"+e.toString());
         }
         return bitmap;
     }

調用:

public ImageView pic;
 .....
 .....
 allData=Analysis(readParse(url));
 Iterator<HashMap<String, Object>> it=allData.iterator();
 while(it.hasNext()){
 Map<String, Object> ma=it.next();
 if((Integer)ma.get("id")==id)
 {
 logo=(String) ma.get("logo");
 bigpic=getHttpBitmap(logo);
 }
 }
 pic.setImageBitmap(bigpic);

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

new Thread() {
             @Override
             public void run() {
                 // 參數列表
                 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                 nameValuePairs.add(new BasicNameValuePair("currPage", Integer
                         .toString(1)));
                 nameValuePairs.add(new BasicNameValuePair("pageSize", Integer
                         .toString(5)));
                 try {
                     String result = doPost(nameValuePairs, POST_URL);                    
                     Message msg = handler.obtainMessage(1, 1, 1, result);
                     handler.sendMessage(msg);                     // 發送消息
                 } catch (Exception e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
         }.start();

         // 定義Handler對象
         handler = new Handler() {
             public void handleMessage(Message msg) {
                 switch (msg.what) {
                 case 1:{
                     // 處理UI
                     StringBuffer strbuf = new StringBuffer();
                     List<HashMap<String, Object>> lists = null;
                     try {
                         lists = MainActivity.this
                                 .parseJson(msg.obj.toString());
                     } catch (Exception e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
                     }
                     List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
                     for(HashMap<String, Object> news : lists){
                         HashMap<String, Object> item = new HashMap<String, Object>();
                         item.put("id", news.get("id"));
                         item.put("ItemText0", news.get("name"));

                         try {
                             bitmap = ImageService.getImage(news.get("logo").toString());
                         } catch (Exception e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                         }
                         if(bitmap==null){
                             Log.i("bitmap", ""+bitmap);
                             Toast.makeText(MainActivity.this, "圖片載入錯誤", Toast.LENGTH_SHORT)
                             .show();                                         // 顯示圖片編號
                         }
                         item.put("ItemImage",bitmap);
                         data.add(item);
                     }

                     //生成適配器的ImageItem <====> 動態數組的元素,兩者一一對應
                     MySimpleAdapter saImageItems = new MySimpleAdapter(MainActivity.this, data, 
                             R.layout.d_travelagence_item, 
                             new String[] {"ItemImage", "ItemText0", "ItemText1"}, 
                             new int[] {R.id.lxs_item_image, R.id.lxs_item_text0, R.id.lxs_item_text1});
                     //添加並且顯示
                     gridview.setAdapter(saImageItems);
                 }
                     break;
                 default:
                     break;
                 }                 

             }
         };

 


       

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • NavigatorIOS包裝了UIKit的導航功能,可以使用左劃功能來返回到上一界面。本組件並非由Facebook官方開發組維護。這一組件的開發完全由社區主導。如果純js的方案能夠滿足你的需求的話,那麼我們建議你選擇Navigator組件(理論知識可以見React Native中文網)。 一:概念內 ...
  • package com.example.mvp; import cn.ljuns.temperature.view.TemperatureView;import presenter.ILoginPresenter;import presenter.LoginPresenterCompl;import ...
  • 在Android Studio 當中,如果你選擇的SDK的版本 與你所顯示的視圖版本不一致時,會出現這個錯誤 Exception raised during rendering:com/android/util/PropertiesMap (Details) 如下圖所示 這個時候就得註意你的SDK版 ...
  • 由於項目的需要,系統的彈出框已經不能滿足我們的需求,我們需要各式各樣的彈出框,這時就需要我們去自定義彈出框了。 新建佈局文件 dialog_layout.xml,將下麵內容複製進去 <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:a ...
  • 仿造美圖秀秀移動滑鼠調整seekbar,調整圖片的顏色 項目佈局如下: 效果如下: 邏輯部分代碼如下: 運行效果: ...
  • 安裝eclipse for android 時候的錯誤記錄,轉載自:http://blog.csdn.net/chenyufeng1991/article/details/47442555 (1)打開Preferences,在Windows下麵應該在WIndow-->Preferences.在mac ...
  • Android的SharedPreferences用來存儲一些鍵值對, 但是卻不支持跨進程使用. 跨進程來用的話, 當然是放在資料庫更可靠啦, 本文主要是給作者的新庫[PreferencesProvider](https://github.com/mengdd/PreferencesProvider... ...
  • 原諒我只提供一個鏈接,我在這裡寫了兩遍,最後加個鏈接頁面卡死了,下麵的demo,最好真機調試。(寫博客還是在別的地方寫複製到這裡比較好!) https://pan.baidu.com/s/1mi2fHDu 另外還有一些資料分享,喜歡的可以看一下:http://www.cnblogs.com/ljcg ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...