【问题标题】:Building a library that uses Retrofit internally, wrapping responses构建一个在内部使用 Retrofit 的库,包装响应
【发布时间】:2016-05-02 18:15:05
【问题描述】:

我正在尝试构建一个基本上包装我们的 api 的库。基本上,我想要的结构是这样的:

MySDK mySDK = new MySDK("username", "password");

mySDK.getPlaylistInfo("3423", 2323, new CustomCallback<>(){

//on response
//on failure

});

因此,使用 vanilla Retrofit,api 调用通常如下所示:

ApiService api = retrofit.create(ApiService.class);
Call<Response> call = api.getPlaylistInfo()
call.enqueue(new Callback<Response>() {
    @Override
    public void onResponse(Call<Response> call, Response<Response> response) {
        //handle response
    }

    @Override
    public void onFailure(Call<Response> call, Throwable t) {
        //handle failure
    }

});

基本上,我将如何将改造回调系统封装到我自己的系统中?请注意,需要这样做的原因是在传递最终响应之前对从 api 返回的数据进行预处理。

【问题讨论】:

    标签: java android interface retrofit retrofit2


    【解决方案1】:

    我写了一些类似的东西,所以它可能会帮助你入门,这遵循我为 Volley 编写的实现,并在我迁移到 Retrofit2 时重新使用,所以它类似于它 (this SO question)。

    创建一个全局对象(您将称为 MySDK)作为处理您的请求的单例类:

    创建一个单例类,在应用程序启动时将其实例化:

    public class NetworkManager
    {
        private static final String TAG = "NetworkManager";
        private static NetworkManager instance = null;
    
        private static final String prefixURL = "http://some/url/prefix/";
    
        //for Retrofit API
        private Retrofit retrofit;
        private ServicesApi serviceCaller;
    
        private NetworkManager(Context context)
        {
            retrofit = new Retrofit.Builder().baseUrl(prefixURL).build();
            serviceCaller = retrofit.create(ServicesApi.class);
            //other stuf if you need
        }
    
        public static synchronized NetworkManager getInstance(Context context)
        {
            if (null == instance)
                instance = new NetworkManager(context);
            return instance;
        }
    
        //this is so you don't need to pass context each time
        public static synchronized NetworkManager getInstance()
        {
            if (null == instance)
            {
                throw new IllegalStateException(NetworkManager.class.getSimpleName() +
                        " is not initialized, call getInstance(...) first");
            }
            return instance;
        }
    
        public void somePostRequestReturningString(Object param1, final SomeCustomListener<String> listener)
        {
            String url = prefixURL + "this/request/suffix";
    
            Map<String, Object> jsonParams = new HashMap<>();
            jsonParams.put("param1", param1);
    
            Call<ResponseBody> response;
            RequestBody body;
    
            body = RequestBody.create(okhttp3.MediaType.parse(JSON_UTF), (new JSONObject(jsonParams)).toString());
            response = serviceCaller.thePostMethodYouWant("someUrlSufix", body);
    
            response.enqueue(new Callback<ResponseBody>()
            {
                @Override
                public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> rawResponse)
                {
                    try
                    {
                      String response = rawResponse.body().string();
    
                      // do what you want with it and based on that...
                      //return it to who called this method
                      listener.getResult("someResultString");
                    }
                    catch (Exception e)
                    {
                     e.printStackTrace();
                     listener.getResult("Error1...");
                    }
                }  
                @Override
                public void onFailure(Call<ResponseBody> call, Throwable throwable)
                {
                    try
                    {
                     // do something else in case of an error
                     listener.getResult("Error2...");
                    }
                    catch (Exception e)
                    {
                     throwable.printStackTrace();
                     listener.getResult("Error3...");
                    }
                }
            });
        }
    
        public void someGetRequestReturningString(Object param1, final SomeCustomListener<String> listener)
        {
            // you need it all to be strings, lets say id is an int and name is a string
            Call<ResponseBody> response = serviceCaller.theGetMethodYouWant
                (String.valueOf(param1.getUserId()), param1.getUserName());
    
            response.enqueue(new Callback<ResponseBody>()
            {
                @Override
                public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> rawResponse)
                {
                    try
                    {
                      String response = rawResponse.body().string();
    
                      // do what you want with it and based on that...
                      //return it to who called this method
                      listener.getResult("someResultString");
                    }
                    catch (Exception e)
                    {
                     e.printStackTrace();
                     listener.getResult("Error1...");
                    }
                }  
                @Override
                public void onFailure(Call<ResponseBody> call, Throwable throwable)
                {
                    try
                    {
                    // do something else in case of an error
                     listener.getResult("Error2...");
                    }
                    catch (Exception e)
                    {
                     throwable.printStackTrace();
                     listener.getResult("Error3...");
                    }
                }
            });
        }
    }
    

    这适用于您的界面(例如 POST 和 GET 请求,GET 可能没有参数):

     public interface BelongServicesApi
     {
        @POST("rest/of/suffix/{lastpart}") // with dynamic suffix example
        Call<ResponseBody> thePostMethodYouWant(@Path("lastpart") String suffix, @Body RequestBody params);
    
        @GET("rest/of/suffix") // with a fixed suffix example
        Call<ResponseBody> theGetMethodYouWant(@Query("userid") String userid, @Query("username") String username);
     }
    

    当您的应用程序出现时:

    public class MyApplication extends Application
    {
      //...
    
        @Override
        public void onCreate()
        {
            super.onCreate();
            NetworkManager.getInstance(this);
        }
    
     //...
    
    }
    

    一个简单的回调监听器接口(单独的文件会很好):

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

    最后,无论你想要什么,上下文都已经存在,只需调用:

    public class BlaBla
    {
        //.....
    
            public void someMethod()
            {
                //use the POST or GET 
                NetworkManager.getInstance().somePostRequestReturningString(someObject, new SomeCustomListener<String>()
                {
                    @Override
                    public void getResult(String result)
                    {
                        if (!result.isEmpty())
                        {
                         //do what you need with the result...
                        }
                    }
                });
            }
    }
    

    您可以将任何对象与侦听器一起使用,只需将响应字符串解析为相应的对象,具体取决于您需要接收的内容,您可以从任何地方调用它(onClicks 等),只需记住需要匹配的对象方法之间。

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多