somebodyoneday 2017-02-15
创建一个AsyncHttpClient;
(可选的)通过RequestParams对象设置请求参数;
调用AsyncHttpClient的某个get方法,传递你需要的(成功和失败时)callback接口实现,一般都是匿名内部类,实现了AsyncHttpResponseHandler,类库自己也提供许多现成的response handler,你一般不需要自己创建
AsyncHttpClient类通常用在android应用程序中创建异步GET, POST, PUT和DELETE HTTP请求,请求参数通过RequestParams实例创建,响应通过重写匿名内部类ResponseHandlerInterface方法处理。
如下代码展示了使用AsyncHttpClient与AsyncHttpResponseHandler的基础操作:
AsyncHttpClient client = new AsyncHttpClient(); String path = ""; RequestParams params = new RequestParams(); params.put("username", username); params.put("password", password); client.get(path, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int i, Header[] headers, byte[] bytes) { } @Override public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) { } });
try { JSONObject jsonObject = new JSONObject(); jsonObject.put("username", "ryantang"); StringEntity stringEntity = new StringEntity(jsonObject.toString()); client.post(mContext, "http://api.com/login", stringEntity, "application/json", new JsonHttpResponseHandler(){ @Override public void onSuccess(JSONObject jsonObject) { super.onSuccess(jsonObject); } }); } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }