Retrofit中如何使用Protobuf转换器

How to use Protobuf converter in Retrofit

我读到 protocol buffer (Protobuf) 是一种语言中立、平台中立的可扩展机制,用于序列化结构化数据。我想将它与 retrofit2.0 一起使用。我没有看到任何使用 Protobuf 转换器的改造示例。

请提出一些关于如何在 android 中使用 retrofit2.0

的想法

尽管它比标准 XML 和 JSON 更快更简单,但为什么开发人员不习惯?

  1. 列表项

到了吗?

根据我对你所问内容的了解,我将给出一个粗略的答案。

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

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

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

当执行您的 Asynchronous/Synchronous 请求时,响应在 Response class 中返回,信息在响应的 body() 方法中。

作为示例,我将仅使用 Google site 上 Protocol Buffers 文档中的 Person protobuf。

一步一步:

第 1 步 - 界面

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

第 2 步 -- 服务

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

第 3 步 - POJO

假设您有一个名为 PersonProto.java 的已编译 protobuf Java class 文件。这将是您的 POJO。 (这很简单)

最后,执行异步调用(比如,在您的 MainActivity class 中):

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");
        }
   });
}

希望这能回答你的问题,我有点把它放在一起了。