我知道这一定很简单,但我很困惑。我在我的项目中使用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中添加默认操作?
答案 0 :(得分:3)
您应该创建一个扩展TokenHttpResponseHandler
而不是JsonHttpResponseHandler
的类(比如AsyncHttpClient
),并以这种方式将其传递给客户AsyncHttpClient client.post(url, params, new TokenHttpResponseHandler() {...
。
然后在TokenHttpResponseHandler
中,您可以覆盖OnSuccess
或OnFailure
并设置其默认行为。
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
并在您的通话中使用该课程。