网络请求可以使用开源框架XUtils:
使用方法如下:
<pre name="code" class="java">HttpUtils httpUtils = new HttpUtils();
//<span style="font-family: Arial, Helvetica, sans-serif;"> GlobalContants.CATEGORIES_URL是请求数据的地址</span>
httpUtils.send(HttpMethod.GET, GlobalContants.CATEGORIES_URL, new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo responseInfo) {
result = (String) responseInfo.result;
Log.e("tag", result);
}
@Override
public void onFailure(HttpException error, String msg) {
Toast.makeText(mActivity, "请求失败", 0).show();
error.printStackTrace();
}
});
解析JSON数据可以使用Gson
使用方法:
Gson gson = new Gson();//初始化
NewsData data = gson.fromJson(result, NewsData.class);//result为请求后返回的JSON数据,可以直接使用XUtils获得,NewsData.class为一个bean.如以下数据:
<pre name="code" class="html"><pre name="code" class="java">{
"retcode": 200,
"data":
[
{
"id": 10000,
"title": "新闻",
"type": 1,
"children":
[
{
"id": 10007,
"title": "北京",
"type": 1,
"url": "/10007/list_1.json"
},
{
"id": 10006,
"title": "中国",
"type": 1,
"url": "/10006/list_1.json"
},
{
"id": 10008,
"title": "国际",
"type": 1,
"url": "/10008/list_1.json"
},
{
"id": 10010,
"title": "体育",
"type": 1,
"url": "/10010/list_1.json"
},
{
"id": 10091,
"title": "生活",
"type": 1,
"url": "/10091/list_1.json"
},
{
"id": 10012,
"title": "旅游",
"type": 1,
"url": "/10012/list_1.json"
},
{
"id": 10095,
"title": "科技",
"type": 1,
"url": "/10095/list_1.json"
},
{
"id": 10009,
"title": "军事",
"type": 1,
"url": "/10009/list_1.json"
},
{
"id": 10093,
"title": "时尚",
"type": 1,
"url": "/10093/list_1.json"
},
{
"id": 10011,
"title": "财经",
"type": 1,
"url": "/10011/list_1.json"
},
{
"id": 10094,
"title": "育儿",
"type": 1,
"url": "/10094/list_1.json"
},
{
"id": 10105,
"title": "汽车",
"type": 1,
"url": "/10105/list_1.json"
}
]
},
{
"id": 10002,
"title": "专题",
"type": 10,
"url": "/10006/list_1.json",
"url1": "/10007/list1_1.json"
},
{
"id": 10003,
"title": "组图",
"type": 2,
"url": "/10008/list_1.json"
},
{
"id": 10004,
"title": "互动",
"type": 3,
"excurl": "",
"dayurl": "",
"weekurl": ""
}
]
}
写成bean为:
public class NewsData {
public int retcode;
public ArrayList<NewsMenuData> data;
public class NewsMenuData {
public String id;
public String title;
public int type;
public String url;
public ArrayList<NewsTabData> children;
@Override
public String toString() {
return "NewsMenuData [title=" + title + ", children=" + children + "]";
}
}
public class NewsTabData {
public String id;
public String title;
public int type;
public String url;
}
@Override
public String toString() {
return "NewsData [data=" + data + "]";
}
}