构建一个内部使用Retrofit的库,包装响应

时间:2016-05-02 18:15:06

标签: java android interface retrofit retrofit2

我试图建立一个基本上包裹我们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返回的数据。

1 个答案:

答案 0 :(得分:1)

我已经写了类似的东西,所以它可能会帮助你入门,这是我为Volley写的一个实现,并在我迁移到Retrofit2时重新使用,因此它类似于它({{3} })。

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

创建一个单例类,当你的应用程序启动时你可以实例化它:

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等),只需记住需要匹配的对象方法之间。

希望这有帮助!

相关问题