监听器函数内部AsyncHttpClient的用法(以及这些函数的重用)

时间:2019-01-28 00:26:32

标签: java android listener android-async-http

我正在将LoopJ的AsynHttpClient用于我的Android / Java应用。

在执行了第一批命令之后,我对服务器进行了登录调用。如果可以,我调用其他API来检索数据。

就目前而言,在上一个API正常结束后,我正在调用下一个API。只有在完成最后一次通话后,我才会将应用发送到下一个意图。这是最好的方法吗?

第二个问题,如何处理failure-send_refresh_call-retry API?

最后,有没有一种方法可以只编写一个足够智能的侦听器,以发现何时所有请求都得到答复,然后继续下一个意图?

public void clickLogin(View view) {

[...]

    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams rp = new RequestParams();
    rp.add("grant_type", "password");
    rp.add("username", String.valueOf(txtUsuario.getText()));
    rp.add("password", String.valueOf(txtSenha.getText()));
    rp.add("client_id", "mobileApp");
    HttpUtils.postEncoded("token", rp, new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);

            [...]

            HttpUtils.get(getApplicationContext(),"api/coins", headers, reqparams, new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                    super.onSuccess(statusCode, headers, response);
                    [...]
                    HttpUtils.get(getApplicationContext(),"api/travels", headers, reqparams, new JsonHttpResponseHandler() {

                        @Override
                        public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                            super.onSuccess(statusCode, headers, response);

                            Intent intent = new Intent(getApplicationContext(), TravelsActivity.class);
                            startActivity(intent);
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                            super.onFailure(statusCode, headers, throwable, errorResponse);
                            if (statusCode == 401) {
// *** Treat unauthorized. Call other API to refresh token ***
                            }
                            else {
                                e.printStackTrace();
                            }
                        }
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    super.onFailure(statusCode, headers, throwable, errorResponse);
                    if (statusCode == 401) {
// *** Treat unauthorized. Call other API to refresh token ***
                    }
                    else {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

0 个答案:

没有答案