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

我正在尝试构建一个基本上包装我们的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 call = api.getPlaylistInfo() call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { //handle response } @Override public void onFailure(Call call, Throwable t) { //handle failure } }); 

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

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

创建一个全局对象(您将其称为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 listener) { String url = prefixURL + "this/request/suffix"; Map jsonParams = new HashMap<>(); jsonParams.put("param1", param1); Call response; RequestBody body; body = RequestBody.create(okhttp3.MediaType.parse(JSON_UTF), (new JSONObject(jsonParams)).toString()); response = serviceCaller.thePostMethodYouWant("someUrlSufix", body); response.enqueue(new Callback() { @Override public void onResponse(Call call, retrofit2.Response 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 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 listener) { // you need it all to be strings, lets say id is an int and name is a string Call response = serviceCaller.theGetMethodYouWant (String.valueOf(param1.getUserId()), param1.getUserName()); response.enqueue(new Callback() { @Override public void onResponse(Call call, retrofit2.Response 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 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 thePostMethodYouWant(@Path("lastpart") String suffix, @Body RequestBody params); @GET("rest/of/suffix") // with a fixed suffix example Call 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 { public void getResult(T object); } 

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

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

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

希望这可以帮助!