ksg*_*rkn 6 performance android response retrofit retrofit2
我希望以单一方法处理我的所有回复。目的是在响应代码不是 3 时调用服务,当响应代码为 3 时,我打算先刷新令牌,然后再调用相同的服务。
我创建了一个Basecallback类来捕获一个方法,但我看不到日志,也无法捕获断点。
BASECALLBACK.class
public class BaseCallBack<T> implements Callback<T> {
@Override
public void onResponse(Call<T> call, Response<T> response) {
if (!response.isSuccessful()){
Log.d("BaseCallback","Response Fail");
}
}
@Override
public void onFailure(Call<T> call, Throwable t) {
t.toString();
}
}
Run Code Online (Sandbox Code Playgroud)
调用方法
ApiManager.getInstance().getUsers().enqueue(new BaseCallBack<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
if (response.isSuccessful()){
}
}
@Override
public void onFailure(Call<List<User>> call, Throwable t) {
}
});
Run Code Online (Sandbox Code Playgroud)
我只想处理我的服务单一方法。
您的起点很好 - 您有一个ApiManager您正在寻找的单点 - a class,而不是 a method(在这种情况下,方法不应该是单个联系点,它会使您的代码不可读并且以后更难调试。
从这里开始,使用您自己的自定义界面可能会更好,并根据您的意愿从您调用请求的位置实现它,在那里您可以处理您想要的东西,这是一个非常通用的示例,应该修复一些东西并让您去。
请注意,这仍然需要您工作 - 调整并添加您需要的东西。
这就是你作为一个界面所需要的(非常基本的,你可以添加东西)
public interface CustomCallListener<T>
{
public void getResult(T object);
}
Run Code Online (Sandbox Code Playgroud)
这就是你应该如何在你的 ApiManager 中使用它 - 它接收你的接口作为携带预期对象类型的参数,当响应返回时做你需要的 - 解析它,剪切它,无论如何 - 并将其转换为正确的对象,这示例使用 String 响应和 List 返回对象,您可以期待任何您的想法并相应地解析它,Retrofit2 允许您直接解析 JSON 字符串(使用 GSON 或其他一些库),因此您可以决定在这里使用什么 - 如果你不知道我的意思 - 阅读它。
这也是我将添加断点和Log.调用的地方,以调试您获得的响应,您还可以分解rawResponse标题和其他内容。
class ApiManager
{
// .. other stuff you need...
public void getSomeList(final CustomCallListener<List<SomeObject>> listener)
{
Call<ResponseBody> request = serviceCaller.getSomeInfo(userid);
//...other stuff you might need...
request.enqueue(new Callback<ResponseBody>()
{
@Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> rawResponse)
{
try
{
String response = rawResponse.body().string();
//...other stuff you might need...
//...do something with the response, convert it to
//return the correct object...
SomeObject object = new SomeObject(response);
listener.getResult(object);
}
catch (Exception e)
{
// .. the response was no good...
listener.getResult(null);
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable throwable)
{
// .. the response was no good...
listener.getResult(null);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
最后,这是您应该在代码中的任何位置使用的内容 - 这允许您在那里实现回调并通过从ApiManager.
ApiManager.getInstance().getSomeList(new CustomCallListener<List<SomeObject>>()
{
@Override
public void getResult(List<SomeObject> objects)
{
if (null != objects)
{
// check objects and do whatever...
}
else
{
// ... do other stuff .. handle failure codes etc.
}
}
});
Run Code Online (Sandbox Code Playgroud)
注意事项
如前所述 - 这是一个非常通用的框架,可以进行很大的修改(向接口添加更多具有不同返回类型的方法来处理异常、错误响应、其他对象,向同一方法添加更多参数以处理更多选项等)阅读更多关于这个主题的信息,小心传递空对象,使用 try 和 catches 来避免崩溃。
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
10774 次 |
| 最近记录: |