欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

android客戶端從服務(wù)器端獲取json數(shù)據(jù)并解析的實(shí)現(xiàn)代碼

 更新時(shí)間:2013年06月05日 19:13:56   作者:  
今天總結(jié)一下android客戶端從服務(wù)器端獲取json數(shù)據(jù)的實(shí)現(xiàn)代碼,需要的朋友可以參考下

首先客戶端從服務(wù)器端獲取json數(shù)據(jù)

1、利用HttpUrlConnection

復(fù)制代碼 代碼如下:

/**
      * 從指定的URL中獲取數(shù)組
      * @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獲取到寫的數(shù)據(jù) 
             }

2、利用HttpClient

復(fù)制代碼 代碼如下:

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

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

         return result;
     }

其次Json數(shù)據(jù)解析:
json數(shù)據(jù):[{"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"}]

復(fù)制代碼 代碼如下:

/**
      * 解析
      *
      * @throws JSONException
      */
     private static ArrayList<HashMap<String, Object>> Analysis(String jsonStr)
             throws JSONException {
         /******************* 解析 ***********************/
         JSONArray jsonArray = null;
         // 初始化list數(shù)組對(duì)象
         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數(shù)組對(duì)象
             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;
     }

最后數(shù)據(jù)適配:

1、TextView

復(fù)制代碼 代碼如下:

/**
  * readParse(String)從服務(wù)器端獲取數(shù)據(jù)
  * Analysis(String)解析json數(shù)據(jù)
  */
     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:

復(fù)制代碼 代碼如下:

/**
      * ListView 數(shù)據(jù)適配
      */
     private void product_data(){
         List<HashMap<String, Object>> lists = null;
         try {
             lists = Analysis(readParse(url));//解析出json數(shù)據(jù)
         } 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());//圖片從服務(wù)器上獲取
             } catch (Exception e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
             if(bitmap==null){
                 Log.i("bitmap", ""+bitmap);
                 Toast.makeText(TravelLine.this, "圖片加載錯(cuò)誤", Toast.LENGTH_SHORT)
                 .show();                                         // 顯示圖片編號(hào)
             }
             item.put("logo",bitmap);
             data.add(item);
         }
              listItemAdapter = new MySimpleAdapter1(TravelLine.this,data,R.layout.a_travelline_item,
                         // 動(dòng)態(tài)數(shù)組與ImageItem對(duì)應(yīng)的子項(xiàng)
                         new String[] { "logo", "biaoTi",
                                 "xianJia", "yuanJia", "chuXingTianShu"},
                         // ImageItem的XML文件里面的一個(gè)ImageView,兩個(gè)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);
                 //添加點(diǎn)擊  
                 listview.setOnItemClickListener(new OnItemClickListener() {   
                     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
                             long arg3) {  
                         login_publicchannel_trl_sub(arg2);
                     }  
                 });
     }

對(duì)于有圖片的要重寫適配器

復(fù)制代碼 代碼如下:

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]));///////////關(guān)鍵是這句!!!!!!!!!!!!!!!

             }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);

        

     } */

 }

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

ImageService工具類

復(fù)制代碼 代碼如下:

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 {

     /**
      * 獲取網(wǎng)絡(luò)圖片的數(shù)據(jù)
      * @param path 網(wǎng)絡(luò)圖片路徑
      * @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協(xié)議連接對(duì)象
         conn.setConnectTimeout(5000);
         conn.setRequestMethod("GET");
         if(conn.getResponseCode() == 200){
             InputStream inStream = conn.getInputStream();
             bitmap = BitmapFactory.decodeStream(inStream);
         }
         return bitmap;
     }

     /**
      * 讀取流中的數(shù)據(jù) 從url獲取json數(shù)據(jù)
      * @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處獲取網(wǎng)絡(luò)數(shù)據(jù)寫在了工具類ImageService中方面調(diào)用,因?yàn)槎际且粯拥摹?/P>

當(dāng)然也可以在Activity類中寫一個(gè)獲取服務(wù)器圖片的函數(shù)(當(dāng)用處不多時(shí))

復(fù)制代碼 代碼如下:

/*

      * 從服務(wù)器取圖片
      * 參數(shù):String類型
      * 返回:Bitmap類型

      */

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

調(diào)用:

復(fù)制代碼 代碼如下:

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);

另附 下載數(shù)據(jù)很慢時(shí)建立子線程并傳參:

復(fù)制代碼 代碼如下:

new Thread() {
             @Override
             public void run() {
                 // 參數(shù)列表
                 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);                     // 發(fā)送消息
                 } catch (Exception e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
         }.start();

         // 定義Handler對(duì)象
         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, "圖片加載錯(cuò)誤", Toast.LENGTH_SHORT)
                             .show();                                         // 顯示圖片編號(hào)
                         }
                         item.put("ItemImage",bitmap);
                         data.add(item);
                     }

                     //生成適配器的ImageItem <====> 動(dòng)態(tài)數(shù)組的元素,兩者一一對(duì)應(yīng)
                     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;
                 }                

             }
         };

相關(guān)文章

最新評(píng)論