如何在Retrofit中使用Protobuf转换器

ABI*_*ABI 6 android protocol-buffers retrofit

我读到协议缓冲区(protobuf)是语言中立的,平台中立的可扩展机制,用于序列化结构化数据.我想用retrofit2.0来使用它.我没有看到使用protobuf转换器的任何改进示例.

请通过retrofit2.0建议一些关于如何在android中使用它的想法

即使它比标准的XML和JSON更快更简单,为什么开发人员不能使用它呢?

mas*_*amr 9

根据我的理解你会问我将给出一个粗略的答案.

在Android中使用Retrofit的基本设置要求:

  1. 接口 - 定义API调用
  2. 服务 - 构建HTTP请求端点
  3. POJO - 使HTTP请求(通常是GET请求)适应应用程序中的可用数据

我假设你知道如何处理XML和JSON请求.我用这个参考来学习XML的东西.使用protobuf转换器背后的想法与GSON/simpleXML转换器相同.唯一的区别在于用于调整请求数据的POJO.Java中protobuf的本质是它已经在某种意义上被设置为POJO.

执行异步/同步请求时,将在Response类中返回响应,并且信息位于body()响应方法中.

作为一个例子,我将使用Google网站上的Protocol Buffers文档中的Person protobuf .

一步步:

第1步 - 界面

  public interface IPersonService {
    @GET("/api/v1.0/person/{personId}")
    Call<PersonProto> getPerson(String personId);
  }
Run Code Online (Sandbox Code Playgroud)

第2步 - 服务

private IPersonService setupAdapter() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(API_URL_STRING)
            .addConverterFactory(ProtoConverterFactory.create())
            .build();
    return retrofit.create(IPersonService.class);
}
Run Code Online (Sandbox Code Playgroud)

第3步 - POJO

假设您有一个已编译的protobuf Java类文件PersonProto.java.这将是你的POJO.(那很简单)

最后,执行异步调用(例如,在MainActivity类中):

public void getUser(String personId) {

   setupAdapter().getPerson(personId).enqueue(new Callback<PersonProto>() {
        @Override
        public void onResponse(Response<PersonProto> response, Retrofit retrofit) {
            Log.i(LOG_TAG, "We hit the server");

            if(response.body() != null) {
                //respoonse.body() is your PersonProto Object
                Log.d(LOG_TAG, reponse.body().getName()); //If you see this, you're all set to consume your API
            }
        }

        @Override
        public void onFailure(Throwable t) {
            Log.e(LOG_TAG, "We did not hit the server");
        }
   });
}
Run Code Online (Sandbox Code Playgroud)

希望这能回答你的问题,我有点把它扔到一起tbh.