今天总结一下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;

}

}

};

(转)android客户端从服务器端获取json数据并解析的实现代码的更多相关文章

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

    今天总结一下android客户端从服务器端获取json数据的实现代码,需要的朋友可以参考下   首先客户端从服务器端获取json数据 1.利用HttpUrlConnection /** * 从指定的U ...

  2. android客户端从服务器端获取json数据并解析的实现代码(重要)

    首先客户端从服务器端获取json数据 1.利用HttpUrlConnection /** * 从指定的URL中获取数组 * @param urlPath * @return * @throws Exc ...

  3. android通过httpClient请求获取JSON数据并且解析

    使用.net创建一个ashx文件,并response.write  json格式 public void ProcessRequest(HttpContext context) { context.R ...

  4. HttpURLConnection从网上获取Json数据并解析详解

    HttpURLConnection从网上获取Json数据并解析 1.HttpURLConnection请求数据的步骤 (1)构造一个URL接口地址: URL url = new URL("h ...

  5. JQuery 获取json数据$.getJSON方法的实例代码

    这篇文章介绍了JQuery 获取json数据$.getJSON方法的实例代码,有需要的朋友可以参考一下 前台: function SelectProject() { var a = new Array ...

  6. 网络获取json数据并解析

    1.升级流程分析

  7. 菜鸟学习Spring——SpringMVC注解版在服务器端获取Json字符串并解析

    一.概述. SpringMVC在服务端把客户端传过来的JSON字符串,并把JSON字符串转成 JSON对象并取得其中的属性值,这个在项目中经常用到. 二.代码演示. 需要添加的jar包. 2.1 we ...

  8. Android从服务端获取json解析显示在客户端上面

    Android从服务端获取json解析显示在客户端上面 百度经验:jingyan.baidu.com 首先说一下Json数据的最基本的特点,Json数据是一系列的键值对的集合,和XML数据来比,Jso ...

  9. Android客户端和服务器端数据交互

    网上有很多例子来演示Android客户端和服务器端数据如何实现交互不过这些例子大多比较繁杂,对于初学者来说这是不利的,现在介绍几种代码简单.逻辑清晰的交互例子,本篇博客介绍第四种: 一.服务器端: 代 ...

随机推荐

  1. 触发器内insert,delete,update判断执行不同的内容

    create trigger tr_aon afor insert,update,delere asbegin IF EXISTS(SELECT 1 FROM inserted) AND NOT EX ...

  2. bestcoder r44 p3 hdu 5270 ZYB loves Xor II

    这是昨晚队友跟我说的题,不知道当时是什么玄幻的事件发生了,,我看成了两两相乘的XOR 纠结了好长时间间 不知道该怎么办 今天早上看了下这道题,发现是两两相加的XOR  然后就想了想昨晚的思路 发现可做 ...

  3. VC实用小知识总结 (一),转http://blog.csdn.net/myiszjf/article/details/10007431

    在上一篇中,我们以经介绍了程序的流程和框架,在本篇将详细讨论各个功能的实现主要包括 1.获取磁盘信息2.获取目录信息3.获取文件信息4.运行指定文件5.删除指定文件6.删除指定目录7.创建指定目录8. ...

  4. C# XmlSerializer序列化浅析

    C# 中使用 XmlSerializer 实现类和xml文件的序列化和反序列化,使用起来非常简单. C# XmlSerializer实现序列化: XmlSerializer xml = new Xml ...

  5. 容器 SET part2

    (6) insert   STL中为什么提供这样的set的insert呢? 这个成员函数存在的目的是为了插入效率的问题.函数参数中的 __position 只是一个提示值,表示在这个位置附近(可前可后 ...

  6. C程序设计语言练习题1-3

    练习1-3 修改温度转换程序,使之能在转换表的顶部打印一个标题. 代码如下: #include <stdio.h> // 包含标准库的信息. int main() // 定义名为main的 ...

  7. Scala学习笔记--Akka

    待完成 http://www.gtan.com/akka_doc/ http://my.oschina.net/mingdong/blog/297972 http://www.jdon.com/con ...

  8. STL string常用操作指令

    s.insert(pos,args); 在pos之前插入args指定的字符.pos可以是一个下标或一个迭代器.接受下标的版本返回一个指向s的引用;接受迭代器的版本返回指向第一个插入字符的迭代器. s. ...

  9. 测试一下PHP官方的新一代PHP加速插件ZendOpcache的性能及配置

    过程不表,都比较顺利 参考如下URL: http://www.lvtao.net/server/ZendOpcache.html 大家知道目前PHP的缓存插件一般有三个:APC.eAccelerato ...

  10. 韩顺平HTML5教程www.gis520.com

    传智播客.韩顺平.HTML5游戏公开课-坦克大战01.HTML5介绍.HTML5发展.HTML5学习网站推荐.wmv http://dl.vmall.com/c0b7xrkftf 传智播客.韩顺平.H ...