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

时间:2017-11-20 11:02:00

标签: java android inheritance asynchttpclient

我知道这一定很简单,但我很困惑。我在我的项目中使用AsyncHttpClient。我想创建一个新类,比如AsyncHttpClient2,它将扩展AsyncHttpClient。此类当前正在为每个请求添加一个令牌。 我希望如果回复为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不会覆盖超类

中的方法

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

2 个答案:

答案 0 :(得分:3)

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

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

E.g。

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


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

        // PERFORM SOME ACTION HERE

    }
}

答案 1 :(得分:1)

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