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

时间:2021-05-20

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


// 获取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://.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{


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

}
};

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章