Retrofit Flashcards
What is Retrofit?
is a library that provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp
*OkHttp - An HTTP & HTTP/2 client for Android and Java applications
What is OkHttp ?
Initially Android had only two HTTP clients: HttpURLConnection and Apache HTTP Client; for sending and receiving data from the web.
Each of these clients required a lot of boilerplate code to be written inside the AsyncTask or the background thread methods.
OkHttp android provides an implementation of HttpURLConnection and Apache Client interfaces by working directly on a top of java Socket without using any extra dependencies.
Steps Retrofit
- Require Internet permissions
- Add dependencies for retrofit and for converter
- Create Java Classes for Resources (ex. Gson Models)
- manually
- autogeneration: jsonschema2pojo - Creating the Retrofit instance (ex. ApiClient)
- Define the Endpoints (ex. ApiInterface)
- Accessing the API
- create a service of the MyApiEndpointInterface
- call the service asynchronously, or synchronously
- Converters for various serialization formats
TO FROM JSON:
- Gson,
- Moshi,
- Jackson (parse JSON into Java objects)
TO FROM PROTOCOL BUFFERS (think of XML, but smaller, faster, and simpler)
- Protobuf:
- Wire
TO FROM XML
- Simple XML
- Creating Gson Models
Class is created in dependece of JSON response we will be receiving.
*Creating Gson COnverter
CUSTOM OPTIONS
The Gson Builder class enables a variety of different options that help provide more flexibility for the JSON parsing.
GsonBuilder gsonBuilder = new GsonBuilder();
// register type adapters here, specify field naming policy, etc.
Gson Gson = gsonBuilder.create();
OPTION 1. MATCHING VAR NAME TO JSON KEY
But acording to java conventions - CamelCase -so we can use
Solution 1: use @SerializedName(“prod_year”)
int prodYear;
Solution2: set the field naming policy in the Gson library
gsonBuilder.setFieldNamingPolicy
(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
OPTION 2. Mapping Java Date objects:
String DATE_FORMAT = “yyyy-MM-dd”;
.setDateFormat(DATE_FORMAT);
+OTHER OPTIONS
- Creating the Retrofit instance
To send out network requests to an API, we need to use the Retrofit builder class and specify the base URL for the service, also factory for deserializing the response (here using the Gson library)
public static final String BASE_URL = “http://api.myservice.com/”;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
- Define the Endpoints
With Retrofit 2, endpoints are defined inside of an interface, where each endpoint specifies:
- – AN ANNOTATION of the HTTP method (GET, POST, etc.)
- – A METHOD that will be used to execute the network call.
- – PARAMETERES OF THIS METHOD can also have special annotations:(@Path, @Query, @Body, @Header)
- –THE RETURN TYPE which is always a parameterized Call object such as Call.
If you do NOT need ANY TYPE-SPECIFIC response, you return value as Call or Call , both skips the conversion to Java objects, the diference is that using first we can analyze the payload, but using Call it also ignores the response body payload too (which is an advantage
TERMINOLOGY *this card is optional
What means a payload
For example, a JSON web service response that might look like this (formatted for readability): { "status":"OK", "data": { "message":"Hello, world!" } } In this example, the string Hello, world! is the PAYLOAD, the part that the recipient is interested in; the rest, while vital information, is PROTOCOL OVERHEAD.
SPECIAL ANNNOTATIONS FOR METHOD PARAMENTERS
@Path variable substitution for the API endpoint (i.e. username will be swapped for {username} in the URL endpoint).
@Query specifies the query key name with the value of the annotated parameter.
@Body payload for the POST call (serialized from a Java object to a JSON string)
@Header specifies the header with the value of the annotated parameter
- Accessing the API. Asynchronously, or Synchronously
- create a service of the MyApiEndpointInterface
ApiInterface apiService =retrofit.create(ApiInterface.class); - call the service asynchronously, or synchronously
For both ways first are created the Call object:
Call call = apiService.getUser(username);
FOR SYNCHRONOUS Network Calls
use the execute() method
Response response = client.newCall(request).execute();
Note: Because Android disallows network calls on the main thread, you can only make synchronous calls if you do so on a separate thread or a background service. You can use also use AsyncTask for lightweight network calls.
FOR ASYNCHRONOUS Network Calls
use the enqueue() method, and passing an anonymous Callback object that implements both onFailure() and onResponse().
Retrofit will download and parse the API data on a background thread, and then deliver the results back to the UI thread via the onResponse or onFailure method.
Important Tip: OkHttp dispatches the callback on the worker thread, callbacks in Retrofit are dispatched on the main thread making easier to make changes to your views.
RxJava and Retrofit
Retrofit 2 also supports RxJava extensions.
1. Add the adapter to Retrofit Instance, when it is builded:
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
- Instead of creating Call objects, we will use Observable types.
- Create an Observer to handle the response