Mobile Development 22 min read

Master Retrofit: From Basics to Advanced Customizations in Android

This comprehensive guide walks Android developers through Retrofit’s fundamentals, usage patterns, URL configuration, parameter handling, custom converters, call adapters, and advanced techniques like file uploads, mock servers, and RxJava integration, providing code examples and deep insights to master network requests efficiently.

Tencent TDS Service
Tencent TDS Service
Tencent TDS Service
Master Retrofit: From Basics to Advanced Customizations in Android

Android development offers many HTTP libraries, from HttpUrlConnection to Apache HttpClient, Volley, Async Http Client, and Square’s Retrofit, which is praised for its simple interface configuration, powerful extensions, and elegant code structure.

1. Getting Started with Retrofit

Retrofit’s name suggests it is a “plus” version of retrofitting older systems with new technology.

1.1 Overview

Retrofit is a wrapper for RESTful HTTP requests. It does not perform the network request itself; instead it delegates the request to OkHttp (built‑in since 2.0) while handling interface definition, headers, URLs, etc.

1.2 Hello Retrofit

Add the dependency in build.gradle: compile 'com.squareup.retrofit2:retrofit:2.0.2' Define an API interface, e.g. GitHub service:

public interface GitHubService {
    @GET("users/{user}/repos")
    Call<List<Repo>> listRepos(@Path("user") String user);
}

Create the Retrofit instance and the service:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);

Calling service.listRepos("octocat") returns a Call object that can be executed synchronously or asynchronously.

1.3 URL Configuration

Retrofit supports GET, POST, PUT, DELETE, HEAD, PATCH and custom HTTP methods. The final URL is composed from baseUrl and the @GET/@POST path value. The rules for absolute and relative paths are illustrated in the table below.

Absolute path: path="/apath" with baseUrl="http://host:port/a/b"http://host:port/apath Relative path (directory base): path="apath" with baseUrl="http://host:port/a/b/"http://host:port/a/b/apath Relative path (file base): path="apath" with baseUrl="http://host:port/a/b"http://host:port/a/apath Full URL: path="http://host:port/aa/apath" overrides baseUrl.

1.4 Parameter Types

1.4.1 Query & QueryMap

@GET("/list")
Call<ResponseBody> list(@Query("page") int page);

Use @QueryMap for dynamic query parameters.

1.4.2 Field & FieldMap

@FormUrlEncoded
@POST("/")
Call<ResponseBody> example(@Field("name") String name,
                        @Field("occupation") String occupation);
@FieldMap

handles variable numbers of form fields.

1.4.3 Part & PartMap

For file uploads use @Multipart and @Part:

public interface FileUploadService {
    @Multipart
    @POST("upload")
    Call<ResponseBody> upload(@Part("description") RequestBody description,
                             @Part MultipartBody.Part file);
}

Custom converters can turn a File into a MultipartBody.Part automatically.

1.5 Converters

1.5.1 RequestBodyConverter

Implement a FileRequestBodyConverter to convert File to RequestBody and register it with Retrofit:

public class FileRequestBodyConverterFactory extends Converter.Factory {
    @Override
    public Converter<File, RequestBody> requestBodyConverter(Type type,
        Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        return new FileRequestBodyConverter();
    }
}
public class FileRequestBodyConverter implements Converter<File, RequestBody> {
    @Override public RequestBody convert(File file) throws IOException {
        return RequestBody.create(MediaType.parse("application/octet-stream"), file);
    }
}
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .addConverterFactory(new FileRequestBodyConverterFactory())
    .build();

1.5.2 ResponseBodyConverter

Custom ResponseBodyConverter can map a JSON response that does not match the target model, e.g. converting {"err":0,"content":"...","message":"OK"} into a Result object.

2. Retrofit Internals

2.1 Who Executes the Request?

Retrofit creates a dynamic proxy for the API interface. Method calls are intercepted by InvocationHandler.invoke, which builds an OkHttpCall that delegates to OkHttp.

2.2 Full Request Flow

The Call interface defines execute() and enqueue(). OkHttpCall.execute() performs the network request, receives an okhttp3.Response, and parseResponse converts it to a Retrofit Response using the appropriate converters.

2.3 CallAdapter for RxJava

Adding RxJavaCallAdapterFactory.create() to the Retrofit builder enables API methods to return Observable, Single, etc., instead of Call.

3. Advanced Usage

3.1 Simplified File Upload

By providing an arbitrary converter that transforms a custom TypedFile into MultipartBody.Part, developers can upload files without manually creating RequestBody objects.

3.2 Mock Server

Retrofit’s retrofit-mock module allows you to create a MockRetrofit with a NetworkBehavior. Implement a mock API class and delegate calls to it for testing without a real backend.

4. Summary

Retrofit is a powerful, extensible HTTP client for Android. By mastering its core concepts, custom converters, call adapters, and mock server capabilities, developers can handle simple requests to complex scenarios such as file uploads, RxJava integration, and testing with ease.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AndroidNetworkRxJavaMock ServerOkHttpRetrofitCustom Converter
Tencent TDS Service
Written by

Tencent TDS Service

TDS Service offers client and web front‑end developers and operators an intelligent low‑code platform, cross‑platform development framework, universal release platform, runtime container engine, monitoring and analysis platform, and a security‑privacy compliance suite.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.