Home » Android » android – How to use Protobuf converter in Retrofit

android – How to use Protobuf converter in Retrofit

Posted by: admin June 15, 2020 Leave a comment

Questions:

I read that protocol buffer (protobuf) is language neutral, platform neutral extensible mechanism for serialising structured data. I want to use it with retrofit2.0. I don’t see any retrofit examples using protobuf converter.

Please suggest some ideas about how to use it in android with retrofit2.0

Even though it is faster and simpler than the standard XML and JSON, why developers not get use to it?

How to&Answers:

From what I understand from what you’re asking I’m going to give a rough answer.

The basic set up for using Retrofit in Android requires:

  1. An Interface — to define API calls
  2. A Service — to build the HTTP request endpoints
  3. A POJO — to adapt the HTTP request’s (usually a GET request) to usable data within the app

I’m assuming you know how to handle XML and JSON requests. I used THIS reference to learn the XML stuff.
The idea behind using the protobuf converter is the same as the GSON/simpleXML converters.The only difference would be in the POJO used to adapt the request’s data. The nature of a protobuf in Java is that it’s already set up in a sense to be a POJO.

When executing your Asynchronous/Synchronous requests, the response is returned in the Response class, and the information is in the body() method of the response.

As an example I’ll just use the Person protobuf that’s in the documentation for Protocol Buffers on the Google site.

Step by step:

Step 1 – The Interface

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

Step 2 — The Service

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

Step 3 – The POJO

Lets say you have a compiled protobuf Java class file named PersonProto.java. This will be your POJO. (That was easy)

Finally, execute an Asynchronous call (say, in your 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");
        }
   });
}

Hope this answered your question, I kind of threw it together tbh.