Skip to content
Advertisement

why use Retrofit when we have OkHttp

with OkHttp we can make HTTP request then get response from server

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
  .url(url)
  .build();
Response response = client.newCall(request).execute();

then with Gson lib convert response to object we need.

this is from Square/OkHttp doc:

Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks

I read from stackOverFlow

Retrofit uses OkHTTP automatically if available

.

So my question is what is exactly Retrofit for?

what Retrofit can do that OkHttp can not?!

I think OkHttp and Gson solve request API problem, so what problem Retrofit solve for us?

Advertisement

Answer

with OkHttp we can make HTTP request then get response from server… then with Gson lib convert response to object we need

Note that in your code snippet, you skipped two notable steps: generating the URL and actually parsing the JSON using Gson.

So my question is what is exactly Retrofit for?

It is for generating the URL (using type-aware generated code tied to your specific REST API) and actually parsing the JSON using Gson. In other words, it does what you skipped in your code snippet.

Also, for certain types of REST operations (e.g., POST), it helps a bit in assembling what to submit (e.g., generating the encoded form).

By definition, you do not need to use Retrofit. Retrofit is computer code, written by computer programmers. Somebody else could write code to do what Retrofit does.

why Retrofit use OkHttp

Retrofit needs to perform HTTP operations. It uses OkHttp where available, for all that OkHttp provides: HTTP/2 and SPDY support, pluggable interceptors, etc.

10 People found this is helpful
Advertisement