I read that protocol buffer (Protobuf) is a language-neutral, platform-neutral extensible mechanism for serializing 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 do developers not get used?
to it?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With