Android Web Service Client
Alexander Nelson
November 15, 2019
University of Arkansas - Department of Computer Science and Computer Engineering
Java Interfaces
Java Interface
A Java Interface is a collection of related methods with empty
bodies
Typically, a class will implement an interface
This forces the programmer to implement certain methods so that
the class will be type safe
Example
Example Interface and implementing class
Retrofit
Retrofit – HTTP API for Java
Type-safe HTTP Client for Java
Builds API from a Java Interface
Each method is specified with an HTTP annotation and URL
Example:
public interface GitHubService {@GET(“users/user/repos”)
Call<List<Repo>>listRepos(@Path(“user”) String user);
}
Retrofit Instance
Retrofit class generates an implementation of the API from the
defined interface
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(“https://api.github.com/”)
.build();
GitHubService service = retrofit.create(GitHubService.class)
Call Interface
Retrofit implements a generic type Call interface that:
• Performs HTTP requests
• Handles HTTP responses
• Deserializes responses into the Typed class
Example:
Call<List<Repo>> repos =
service.listRepos(“alexanderhnelson”);
Annotations
Interface annotations enable flexible behavior
Describes the HTTP Requests by:
• URL Parameter replacement
• Query parameter support
• Object conversion to request body
• Multipart request body and file upload
API Declaration
Every method must have an HTTP annotation that provides
1. Request method
2. Relative URL of the resource
Built-in request annotations:
• HEAD
• GET
• POST
• PUT
• DELETE
Specifying Parameters
Parameters may be specified in the URL
Example:
@GET(“users/list?sort=desc”)
URL Manipulation
URL can be updated dynamically using replacements and
parameters
A replacement block can be included in the URL
Replacement block defined by a string surrounded by curly braces
“{}”
Example:
@GET(”group/{id}/users”)
Call<List<User>> groupList(@Path(“id”) int groupId);
When this method is called, creates a GET request with the
specified ID
Query Parameters
Query Parameters can be added
(i.e. what shows up after the ? on a REST URL)
Example:
@GET(”group/id/users”)
Call<List<User>> groupList(@Path(“id”) int groupId,
@Query(“sort”) String sort);
Creates a GET at BASE URL/group/id/users?sort=(sort)
Creating Complex Queries
Complex queries can be created using a Map object
@GET(”group/id/users”)
Call<List<User>> groupList(@Path(“id”) int groupId,
@QueryMap Map<String, String> options);
Passing Objects
The HTTP Body can be specified using a Java Object with the
@Body tag
@POST(“users/new”)
Call<User> createUser(@Body User user);
Sending Form Encoded data
Methods can be declared to encode data in form-fields
Use @FormUrlEncoded tag with the HTTP Request
@FormUrlEncoded
@POST(“user/edit”)
Call<User> updateUser(@Field(“first name”) String first,
@Field(“last name”) String last);
Multipart Requests
Create Multipart requests using the @Multipart annotation
Add parts using the @Part annotation in the method definition
Example:
@Multipart
@PUT(”user/photo”)
Call<User> updateUser(@Part(“photo”) RequestBody photo,
@Part(“description”) RequestBody description);
Manipulating Headers
Set static headers for a method with the @Headers annotation
Example:
@Headers({”Accept: application/vnd.github.v3.full+json”,
”User-Agent: Retrofit-Sample-App”
})@GET(”users/{username}”)
Call<User> getUser(@Path(“username”) String username);
Dynamic Headers
Headers can be manipulated dynamically in the method definition
using the @Header tag
Example:
@GET(“user”)
Call<User> getUser(@Header(“Authorization”) String
authorization);
Common Headers
If all requests need the same headers
Use an OkHttp interceptor
https://github.com/square/okhttp/wiki/Interceptors
Retrofit Configuration
Conversion and deserialization
By default, Retrofil will only deseralize to a particular type
(OkHttp ResponseBody)
Allows for conversion to other types using a converter
For JSON, the GSON library is available
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(”my.api.url.com”)
.addConverterFactory(GsonConverterFactory.create())
.build();