首先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 成功 而且 傳回值可以轉成json
public 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
}
});