欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-03 14:33:10
首先客户端从服务器端获取json数据 1、利用httpurlconnection 复制代码 代码如下:/**     ...

首先客户端从服务器端获取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;
                 }                

             }
         };