AsyncHttpClient框架


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.csdn.net/detail/qq602298560/8038833 點擊打開鏈接


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章