扩展 AsyncHTTPClient 以添加默认成功回调

Extend AsyncHTTPClient to add default success callback

我知道这一定很简单,但我很困惑。我在我的项目中使用 AsyncHttpClient。我想创建一个新的 class,比如 AsyncHttpClient2,它将扩展 AsyncHttpClient。 class 目前正在为每个请求添加一个令牌。 我希望如果响应是 UNAUTHORIZED,它应该执行一些操作。

这是 POST 语法:

String url = "https://ajax.googleapis.com/ajax/services/search/images";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("q", "android");
params.put("rsz", "8");
client.post(url, params, new JsonHttpResponseHandler() {            
    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
       // handler code
   }

    @Override
    public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
       // error code
    }
});

这是我的代码:

public class TokenAsyncHttpClient extends AsyncHttpClient {
    public TokenAsyncHttpClient() {
        super();
        this.addHeader("x-access-token", "00000000000000000000000");
    }


    // THIS GIVES ERROR Method does not override method from its superclass

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

        // PERFORM SOME ACTION HERE

    }
}

但这让我在 @Override 行出现以下错误:

Method does not override method from its superclass

我做错了什么?以及如何在 onSuccess 中添加默认操作?

您应该创建一个扩展 JsonHttpResponseHandler 而不是 AsyncHttpClient 的 class(例如 TokenHttpResponseHandler),并以这种方式将其传递给客户端 AsyncHttpClient client.post(url, params, new TokenHttpResponseHandler() {... .

然后在 TokenHttpResponseHandler 中您可以覆盖 OnSuccessOnFailure 并设置其默认行为。

例如

public class TokenHttpResponseHandler extends JsonHttpResponseHandler {
    public TokenHttpResponseHandler() {
        super();
    }


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

        // PERFORM SOME ACTION HERE

    }
}

阅读 documentation line 1094 结果发现 AsyncHttpClient 没有名为 onSuccess 的方法。通过阅读您的问题,您正在使用 class 中的 get 方法,该方法依赖于 ResponseHandlerInterface 具有其 onSuccess 方法,因此如果您想更改此方法的行为您需要在某些 class 中实现 ResponseHandlerInterface 并在您的调用中使用 class。