AsyncHttpClient 是一个框架提供的库 可以异步传输,使用时需下载android-async-http-1.4.4.jar包导入到项目中。
自定义一个工具类RequestClient
public class RequstClient {
private static AsyncHttpClient mClient = new AsyncHttpClient();
static {
mClient.setTimeout(20000);
}
public static void post(String url, AsyncHttpResponseHandler handler) {
post(url, null, handler);
}
public static void post(String url, RequestParams params,
AsyncHttpResponseHandler handler) {
System.out.println("");
mClient.post(url, params, handler);
}
public static void get(String url, AsyncHttpResponseHandler handler) {
}
public static void get(String url, RequestParams params,
AsyncHttpResponseHandler handler) {
System.out.println("get");
mClient.get(url, params, handler);
}
}
解析JSON数据的简便api方式:
RequstClient.post(url,new JsonHttpResponseHandler(){
@Override
public void onSuccess(JSONObject response) {
try {
/*
product
*/
JSONArray array1=response.getJSONArray("Products");//当json数据有多个的时候,得到 //jsonArray对象
for(int i=0;i<array1.length();i++){
JSONObject jsonObject2=array1.getJSONObject(i);
Product product=new Product();
product.setId(jsonObject2.getString("Id"));
product.setName(jsonObject2.getString("Name"));
product.setImage(jsonObject2.getString("Image"));
product.setPrice(jsonObject2.getString("Price"));
product.setTime(jsonObject2.getString("Created"));
data.add(product);
}
JSONObject jsonObject_share=response.getJSONObject("Share");//得到jsonObject对象
share.setTitle(jsonObject_share.getString("Title"));通过api得到json里的数据
share.setDescription(jsonObject_share.getString("Description"));
share.setIcon(jsonObject_share.getString("Icon"));
share.setUrl(jsonObject_share.getString("Url"));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Throwable e, JSONObject errorResponse) {
Log.d("line","error"+statusCode);
super.onFailure(statusCode, e, errorResponse);
}
});
包的下载地址 不需积分: http://download.youkuaiyun.com/detail/qq602298560/8038833 点击打开链接