gpt4 book ai didi

java - 构建内部使用 Retrofit 的库,包装响应

转载 作者:行者123 更新时间:2023-11-30 01:21:44 28 4
gpt4 key购买 nike

我正在尝试构建一个基本上包装我们的 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 返回的数据。

最佳答案

我写了一些类似的东西,所以它可能会帮助你入门,这是我为 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);
}

//...

}

用于回调的简单监听器接口(interface)(单独的文件会很好):

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

希望对您有所帮助!

关于java - 构建内部使用 Retrofit 的库,包装响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36988947/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com