关于android-async-http的使用,封装网络请求

来源:互联网 发布:装修隔墙 知乎 编辑:程序博客网 时间:2024/05/20 13:39

首先async是跟安卓中自带的AsyncTask很像,不过它更简单

异步基于回调的Http客户端为Android构建,是基于Apache HttpClient库的。所有的请求都是位于应用程序主线程 UI 之外,但任何回调逻辑将相同的线程上执行回调,使用Android的处理程序创建消息传递。

首先封装一下AsyncHttpClient,这个jar包中的核心类

public class AsyncHttpRequestClient {      private static AsyncHttpClient client = new AsyncHttpClient();        public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler)     {          client.get(url, params, responseHandler);      }        public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler)     {          client.post(url, params, responseHandler);      }      }
AsyncHttpResponseHandler,负责处理网络请求中的回调

RequestParams, 负责参数的传递


然后封装自己的AsyncHttpResponseHandler的类

public class JSONObjectResponseHandler extends JsonHttpResponseHandler{private Activity parent = null;public JSONObjectResponseHandler(Activity act) {super("utf-8");this.parent = act;}//在调用处 重写该方法   完成自己想做的事情public void onJsonOk(JSONObject response){}//解析json 的时候遇到问题public void onJsonFail(Throwable throwable){Toast.makeText(this.parent, "json解析异常", Toast.LENGTH_SHORT).show();Log.e("net error", "error" ,throwable);}// 200 成功 而且 返回值可以转成jsonpublic void onSuccess(int statusCode, Header[] headers, JSONObject response) {try {//Toast.makeText(this.parent, response.toString(), Toast.LENGTH_SHORT).show();System.out.println(response.toString());                                               //自己去做一写处理                          JSONObject headerJsonObject = response.getJSONObject("header");int err = headerJsonObject.getInt("err");if(err == 0){                             this.onJsonOk(response.getJSONObject("body"));}else{Toast.makeText(this.parent, headerJsonObject.getString("errMsg"), Toast.LENGTH_SHORT).show();}}catch (JSONException e) {e.printStackTrace();        //  onJsonFail(Throwable throwable)          }};<span style="font-family:Palatino Linotype,Palatino,Book Antiqua,serif;">// 请求失败 或者返回值无法 转成json</span>public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable)     {     System.out.println(responseString);//       Log.v("error", responseString);    }}


最后去使用它

         AsyncHttpRequestClient.post(url, params,new JSONObjectResponseHandler(this)            {public void onJsonOk(JSONObject response){                                  //网路请求成功 并得到啦 正确的结果  你现在可以去 解析 response                                                                 }                     });



1 0
原创粉丝点击