JavaFX,Unity3D,Android,IOS等技术教程和生活随笔,仅供记录

http://www.wingmei.cn/wp-content/themes/Vtrois-Kratos-e85a527/images/background.jpg

Android开源库android-async-http

由于业余接了一个android手机客户端的项目,近期一直在做这个,其他的事情暂且放一边了,准备讲一讲android的一些开源库。

android-async-http是一个异步的,基于回调的Http的开源库,用于处理android平台上的http同步和异步请求,回复,同时还包含对于response的JSON解析,是一个非常方便的库。

开源地址:android-async-http

下面我们来看看android-async-http的基本用法:

1.get和post请求

client.post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler);
client.get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler);

android-async-http中的HttpClient的同步和异步分别为:SyncHttpClientAsyncHttpClient,在使用上没有本质区别。只不过SyncHttpClient是同步请求,通常放在线程之中执行,然后再回调函数中通过handler进行UI层的处理。而AsyncHttpClient本身已做过异步处理,调用之后从ResponseHandler的方法中进行其他操作即可。

2.Request的参数

通常进行Request请求会附带参数,在这里我们通过RequestParams来进行请求的参数传递。

RequestParams params = new RequestParams(); 
params.put("key", "value"); 
params.put("more", "data");

3.对于json的Response的处理

在Android中,与服务器交互的数据传输,通常是使用JSON的格式,而在android-async-http中则自带了解析json的ResponseHandler,非常的方便。

WHttpClient.get(StaticData.MoneyQryUrl + StaticData.UserName, new JsonHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
        Log.d(StaticData.App_Tag, "AccountQry");
        Message msg = new Message();
        msg.obj = response;
        msg.what = TypeMoneyQrySuccess;
        handler.sendMessage(msg);
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
        Log.d(StaticData.App_Tag, "AccountQry Failure");
        handler.sendEmptyMessage(TypeMoneyQryError);
    }

});

如上,是将Response返回的数据解析成JSONObject,这是一个包含JSON数据的Object,我们可以通过getDouble,getString,getInt等方法来获取JSON的数据。

另外,上面只是返回一个JSONObject,同样的,我们也可以返回一个包含JSON数据的链表。

WHttpClient.getSync(StaticData.QryOrderHistoryUrl + StaticData.UserName + "/" + dateStr, new JsonHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
        Log.d(StaticData.App_Tag, "Query History Success:" + response.length());
        dealHistoryList.clear();
        for (int i = 0; i < response.length(); i++) {
            DealHistory dealHistory = new DealHistory();
            JSONObject obj = null;
            try {
                obj = response.getJSONObject(i);
                String id = obj.getString("ID");
                String contracteNo = obj.getString("ContracteNo");
                String commodityNo = obj.getString("CommodityNo");
                String orderPrice = obj.getString("OrderPrice");
                String orderVol = obj.getString("OrderVol");
                String orderType = obj.getString("OrderType");
                String direct = obj.getString("Direct");
                int matchPrice = obj.getInt("MatchPrice");
                int matchVol = obj.getInt("MatchVol");

                String validDate = obj.getString("ValidDate");
                String triggerPrice = obj.getString("TriggerPrice");
                String offset = obj.getString("Offset");
                String Guid = obj.getString("Guid");
                String orderDate = obj.getString("OrderDate");
                String orderDateDay = obj.getString("OrderDateDay");
                int state = obj.getInt("State");

                dealHistory.setId(id);
                dealHistory.setContractNo(contracteNo);
                dealHistory.setCommodityNo(commodityNo);
                dealHistory.setOrderPrice(orderPrice);
                dealHistory.setOrderVol(orderVol);
                dealHistory.setOrderType(orderType);
                dealHistory.setMatchPrice(matchPrice);
                dealHistory.setMatchVol(matchVol);
                dealHistory.setDirect(direct);
                dealHistory.setValidDate(validDate);
                dealHistory.setTriggerPrice(triggerPrice);
                dealHistory.setOffset(offset);
                dealHistory.setGuid(Guid);
                dealHistory.setOrderDate(orderDate);
                dealHistory.setOrderDateDay(orderDateDay);
                dealHistory.setState(state);
                dealHistoryList.add(dealHistory);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        handler.sendEmptyMessage(TypeQryOrderHistorySuccess);
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        Log.d(StaticData.App_Tag, "Query History Error:" + throwable.getMessage());
        handler.sendEmptyMessage(TypeQryOrderHistoryError);
    }

});

如上,这个response和上面的一样,使用的JsonHttpResponseHandler来重写回调函数,只不过这里将它返回的数据解析为JSONArray,然后我们通过遍历JSONArray,将JSONObject的数据都填充到我们的Java Bean类中来使用。

以上是我们常用的一些类型,其实android-async-http还包含上传下载Basic Auth认证等等功能,有兴趣的朋友可以自行查阅。

点赞

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注