当前位置:  编程技术>移动开发

android客户端从服务器端获取json数据并解析的实现代码

    来源: 互联网  发布时间:2014-10-17

    本文导语:  首先客户端从服务器端获取json数据 1、利用HttpUrlConnection 代码如下:/**      * 从指定的URL中获取数组      * @param urlPath      * @return      * @throws Exception      */     public static String readParse(String urlPath) throws Exception ...

首先客户端从服务器端获取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(/tech-mobile-dev/urlPath/index.html); 
                 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 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 Analysis(String jsonStr)
             throws JSONException {
         /******************* 解析 ***********************/
         JSONArray jsonArray = null;
         // 初始化list数组对象
         ArrayList list = new ArrayList();
         jsonArray = new JSONArray(jsonStr);
         for (int i = 0; i < jsonArray.length(); i++) {
             JSONObject jsonObject = jsonArray.getJSONObject(i);
             // 初始化map数组对象
             HashMap map = new HashMap();
             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 it = allData.iterator();
             while (it.hasNext()) {
                 Map 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 lists = null;
         try {
             lists = Analysis(readParse(url));//解析出json数据
         } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         List data = new ArrayList();
         for(HashMap news : lists){
             HashMap item = new HashMap();
             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 list; 
     private int layoutID; 
     private String flag[]; 
     private int ItemIDs[]; 
     public MySimpleAdapter1(Context context, List 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(/tech-mobile-dev/imageUrl/index.html);  
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
         InputStream is = conn.getInputStream();  
         mBitmap = BitmapFactory.decodeStream(is);*/
         Bitmap bitmap= null;
         URL url = new URL(/tech-mobile-dev/path/index.html);
         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(/tech-mobile-dev/urlpath/index.html);
             //打开连接
             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 it=allData.iterator();
 while(it.hasNext()){
 Map 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 nameValuePairs = new ArrayList();
                 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 lists = null;
                     try {
                         lists = MainActivity.this
                                 .parseJson(msg.obj.toString());
                     } catch (Exception e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
                     }
                     List data = new ArrayList();
                     for(HashMap news : lists){
                         HashMap item = new HashMap();
                         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;
                 }                

             }
         };

    
 
 

您可能感兴趣的文章:

  • XBMC的Android客户端 android-xbmcremote
  • 白宫Android客户端 wh-app-android
  • android客户端自动升级库 android-autoupdater
  • 搜狐白社会Android客户端 baidroid
  • 饭否Android客户端 安能饭否
  • Android的邮件客户端 K9mail
  • OSCHINA Android 客户端
  • 博客园Android客户端 AndroidCnblogs
  • Android的XMPP客户端 Beem
  • Android的SSH客户端 ConnectBot
  • Android手机的VoIP客户端 Sipdroid
  • last.fm客户端 lastfm-android
  • Android平台上的JXTA客户端 Peerdroid
  • Android中Root权限获取的简单代码 iis7站长之家
  • Android的Git客户端 Agit
  • Android的Twitter客户端 AndTweet
  • MLdonkey的Android客户端 Nulu GUI ML
  • 比特币的 Android 客户端 BitcoinDroid
  • Android下的加密信息客户端 TextSecure
  • Android微博客户端 YiBo
  • 解析ADT-20问题 android support library
  • android layout XML解析错误的解决方法
  • Android入门之TableLayout应用解析(一)
  • 解析:android 如何从JPEG生成BufferedImage
  • 基于Android XML解析与保存的实现
  • 基于android中读取assets目录下a.txt文件并进行解析的深入分析
  • 解析Android应用启动后自动创建桌面快捷方式的实现方法
  • Android入门之TableLayout应用解析(二)
  • 解析Android中string-array数据源的简单使用
  • 解析android创建快捷方式会启动两个应用的问题
  • 解析离线安装Eclipse的Android ADT开发插件的具体操作(图文)
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • Android获取本机电话号码的简单方法
  • android获取手机唯一标识的方法
  • android 如何获取MCC/MNC控制小区广播的开启
  • android当前apn的状态以及获取方法
  • Android手机获取root权限并实现关机重启功能的方法
  • Android获取手机SIM卡运营商信息的方法
  • 用Android Location获取当前地理位置的方法
  • Android取消EditText自动获取焦点默认行为
  • Android获取屏幕方向及键盘状态的小例子
  • android开发中获取手机分辨率大小的方法
  • android获取当前手机号示例程序
  • android开发教程之获取使用当前api的应用程序名称
  • 在Android中 获取正在运行的Service 实例
  • android连接wifi时获取广播地址代码
  • Android获取apk程序签名信息代码示例
  • Android开发之获取网络链接状态
  • android 获取屏幕像素大小的正确方法
  • Android获取应用程序名称(ApplicationName)示例
  • Android中Root权限获取的简单代码
  • android获取屏幕像素思路及代码
  • 申请Android Map 的API Key(v2)的最新申请方式(SHA1密钥)
  • Android瀑布流实例 android_waterfall
  • Android开发需要的几点注意事项总结
  • Android系统自带样式 (android:theme)
  • android 4.0 托管进程介绍及优先级和回收机制
  • Android网络共享软件 Android Wifi Tether
  • Android访问与手机通讯相关类的介绍
  • Android 图标库 Android GraphView
  • Android及andriod无线网络Wifi开发的几点注意事项
  • 轻量级Android开发工具 Android Tools
  • Android 2.3 下StrictMode介绍


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3