Retrofit Flashcards

1
Q

What is Retrofit?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is OkHttp ?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Steps Retrofit

A
  1. Require Internet permissions
  2. Add dependencies for retrofit and for converter
  3. Create Java Classes for Resources (ex. Gson Models)
    - manually
    - autogeneration: jsonschema2pojo
  4. Creating the Retrofit instance (ex. ApiClient)
  5. Define the Endpoints (ex. ApiInterface)
  6. Accessing the API
    • create a service of the MyApiEndpointInterface
    • call the service asynchronously, or synchronously
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
  1. Converters for various serialization formats
A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
  1. Creating Gson Models
A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
  1. Creating the Retrofit instance
A

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();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
  1. Define the Endpoints
A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

TERMINOLOGY *this card is optional

What means a payload

A
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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

SPECIAL ANNNOTATIONS FOR METHOD PARAMENTERS

A

@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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
  1. Accessing the API. Asynchronously, or Synchronously
A
  1. create a service of the MyApiEndpointInterface
    ApiInterface apiService =retrofit.create(ApiInterface.class);
  2. 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

RxJava and Retrofit

A

Retrofit 2 also supports RxJava extensions.
1. Add the adapter to Retrofit Instance, when it is builded:
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

  1. Instead of creating Call objects, we will use Observable types.
  2. Create an Observer to handle the response
How well did you know this?
1
Not at all
2
3
4
5
Perfectly