您的位置:首页 > 理论基础 > 计算机网络

HttpClient解析json(涉及AsyncTas异步加载图片)

2016-06-30 15:22 489 查看
====================utils下的NetWorkUtils==================

package com.example.utils;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;

import android.util.Log;

public class NetWorkUtils {

static String tag = "TAG";

public static String getStr(String htt) {
String path = htt + "18938f9a9808b846aff0801f51d6efde";

HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path);
try {
HttpResponse response = client.execute(get);
int code = response.getStatusLine().getStatusCode();

if (code ==200) {
String result = EntityUtils.toString(response.getEntity());

/*ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = response.getEntity().getContent();

byte[] arr = new byte[1024];
int len = 0;

while ((len = is.read(arr))!=-1) {
baos.write(arr, 0, len,"utf-8");
}*/

return result;

}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

=====================在mainActivity中调用======================

String htt = "http://japi.juhe.cn/comic/book?key=";

/*
* 解析
*/
private void initData() {
new AsyncTask<Void, Void, String>() {

@Override
protected String doInBackground(Void... params) {

return NetWorkUtils.getStr(htt);
}

/**

*相当于子线程

/
@Override
protected void onPostExecute(String result) {

Gson gson = new Gson();
Type type = new TypeToken<BookList>() {
}.getType();

blist = gson.fromJson(result, type);
bl = blist.result.bookList;

// Log.e("TAG", bl.toString());
// 添加适配器,
lv.setAdapter(new MyBaseAdapter(getActivity(),bl));
}
}.execute();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: