Use Retrofit with another request/response protocol in Android

535 Views Asked by At

I want to use Retrofit to adapt responses using another request/response protocol for IoT (not HTTP, but very similar in terms of architecture) in my Android application. Notably, I suppose the other protocol already has an executor, and Retrofit would come in just to adapt the request results in a type-safe fashion.

I saw that the Retrofit Builder function used for passing in the client is strongly coupled to OkHttp:

public Builder client(OkHttpClient client){...}

I have started looking into Retrofit's CallAdapter and CallAdapter.Factory but I do not know if they can work independently from an OkHttp client or if they can bypass this client.

Is there a way to use Retrofit with another request/response protocol?

2

There are 2 best solutions below

0
On BEST ANSWER

I managed to solve this problem rather with OkHttp's Call.Factory and Call interfaces.

First of all, I implemented a custom Call.Factory. The newCall(Request request) method in the Call.Factory is the entry point. An okhttp3.Requestis passed into it and it returns a Call. Here's a high-level example:

override fun newCall(request: Request): Call = CustomCall(request, ...)

The next step is to create a custom call. For that purpose, I used the Call interface. Most methods are quite straightforward, but something to consider is the difference between the methods override fun enqueue(responseCallback: Callback) and fun execute(): Response, which correspond respectively to non-blocking and blocking executions.

Finally it is possible to pass the custom Call.Factory to Retrofit with the following code:

Retrofit.Builder()
        .baseUrl(baseUrl)
        .callFactory(customFactory)
        .build()
        .create(CustomApi::class.java)
1
On

Retrofit is just a nice wrapper around okHttp, but you can always use okhttp directly for your purpose