改造通用响应处理程序 [英] Retrofit generic response handler

查看:70
本文介绍了改造通用响应处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望以单一方法处理我的所有回复.目的是在响应码不是3时召回服务,当响应码是3时我打算先刷新token,然后再召回相同的服务.

I wish to handle all my responses in single method. the purpose is to recall the service when the response code is not 3, when the response code is 3 I intend to first refresh the token and then recall the same service.

我创建了一个 Basecallback 类来捕获一个方法,但我看不到日志,也无法捕获断点.

I've created a Basecallback class to catch one method but I can't see the log and can't catch breakpoints.

BASECALLBACK.class

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();
 }
}

调用方法

 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) {

            }
        });

我只想处理我的服务单一方法.

I just want to handle my services single method.

推荐答案

你的起点很好 - 你有一个 ApiManager 这是你正在寻找的单点 - class,而不是 method(在这种情况下,方法不应该是一个单一的联系点,它会使您的代码不可读并且以后更难调试.

Your starting point is good - you have an ApiManager which is the single point you're looking for - a class, NOT a method (methods shouldn't be a single contact point in this case, it will make your code unreadable and harder to debug later.

从这里开始,使用您自己的自定义界面可能会更好,并根据您的意愿从您调用请求的位置实现它,在那里您可以处理您想要的东西,这是一个非常通用的 应该解决一些问题并让您继续前进的示例.

From here it would probably be better to use your own custom interface, and implement it however you wish from where you call the request, there you can handle the stuff you want, this is a very generic example that should fix some stuff and get you going.

请注意,这仍然需要您进行工作 - 调整并添加您需要的内容.

Be mindful to the fact that this still requires you to work - tweak and add the stuff you need.

这就是你需要的所有界面(非常基本,你可以添加东西)

This is all you need as an interface (very basic, you can add stuff)

public interface CustomCallListener<T>
{
 public void getResult(T object); 
}

这是你应该如何在你的 ApiManager 中使用它 - 它接收你的接口作为携带预期对象类型的参数,当响应返回时执行你需要的操作 - 解析它,剪切它,无论如何 - 并将其转换为正确的对象,此示例使用 String 响应和 List 返回对象,您可以期待任何您认为的内容并相应地解析它,Retrofit2 允许您直接解析 JSON 字符串(使用 GSON 或其他一些库),因此您可以决定使用什么在这里 - 如果你不明白我的意思 - 阅读它.

This is how you should use it in you ApiManager - it receives your interface as a parameter carrying the expected object type, when the response returns do what you need - parse it, cut it, whatever - and cast it into the correct object, this example uses a String response and a List return object, you can expect whatever you think and parse it accordingly, Retrofit2 allows you to parse JSON strings directly (using GSON or some other library), so it's your decision on what to use here - if you don't know what I mean - read about it.

这也是我将添加断点和 Log. 调用以调试您获得的响应的地方,您还可以将 rawResponse 分解为标题和其他内容.

This is also where I would add breakpoints and Log. calls to debug the response you get as you get it you can also break down rawResponse for headers and other stuff.

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);
        }
    });
 }
}

最后,这是您应该在代码中的任何位置使用的内容 - 这允许您在那里实现回调并通过从 ApiManager 返回的内容处理您需要的任何内容.

Finally this is what you should use from anywhere in your code - this allows you to implement the callback right there and handle anything you need by what you return from the 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.
            }
        }
    });

注意事项

如前所述 - 这是一个非常通用的骨架,可以进行很大的修改(向接口添加更多具有不同返回类型的方法来处理异常、错误响应、其他对象,向同一方法添加更多参数以处理更多选项,等)更多地阅读该主题,注意传递空对象,使用 try 和 catch 来避免崩溃.

As mentioned - this is a very generic skeleton that can be greatly modified (add more methods to the interface with different return types to handle Exceptions, Bad responses, other objects, add more params to the same method to handle more options, etc.) read about the subject more, beware of passing null Objects, use try and catches to avoid crashes.

希望这有帮助!

这篇关于改造通用响应处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆