Backend Development 11 min read

Master Retrofit in Spring Boot: Seamless HTTP Client Integration Tutorial

This article walks through integrating the Retrofit HTTP client into Spring Boot applications using the retrofit‑spring‑boot‑starter, covering dependency setup, basic request definitions, token handling, custom interceptors, global logging, timeout and retry configurations, and provides concise code examples for each step.

macrozheng
macrozheng
macrozheng
Master Retrofit in Spring Boot: Seamless HTTP Client Integration Tutorial

Introduction

When developing Java applications, even monolithic ones often need to call external services. Retrofit offers a type‑safe HTTP client for Android and Java, allowing developers to declare interfaces for HTTP requests instead of writing repetitive connection and parsing code.

Dependency Integration

Add the

retrofit-spring-boot-starter

dependency to your Spring Boot project:

<dependency>
  <groupId>com.github.lianjiatech</groupId>
  <artifactId>retrofit-spring-boot-starter</artifactId>
  <version>${retrofit-start.version}</version>
</dependency>

Basic Usage

Define a Retrofit client interface for the Mall project’s admin service:

@RetrofitClient(baseUrl = "${remote.baseUrl}")
public interface UmsAdminApi {
    @POST("admin/login")
    CommonResult<LoginResult> login(@Body LoginParam loginParam);
}

Configure the service address in

application.yml

:

remote:
  baseUrl: http://localhost:8080/

Token Management

Create a

TokenHolder

component that stores the login token in the HTTP session and provides

putToken

and

getToken

methods.

@Component
public class TokenHolder {
    public void putToken(String token) { /* store in session */ }
    public String getToken() { /* retrieve from session */ }
}

Annotation‑Based Interceptor

Implement a

TokenInterceptor

extending

BasePathMatchInterceptor

to add the

Authorization

header to requests that require authentication.

@Component
public class TokenInterceptor extends BasePathMatchInterceptor {
    @Autowired
    private TokenHolder tokenHolder;
    @Override
    protected Response doIntercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (tokenHolder.getToken() != null) {
            request = request.newBuilder()
                .header("Authorization", tokenHolder.getToken())
                .build();
        }
        return chain.proceed(request);
    }
}

Apply the interceptor to the brand API:

@RetrofitClient(baseUrl = "${remote.baseUrl}")
@Intercept(handler = TokenInterceptor.class, include = "/brand/**")
public interface PmsBrandApi {
    @GET("brand/list")
    CommonResult<CommonPage<PmsBrand>> list(@Query("pageNum") Integer pageNum, @Query("pageSize") Integer pageSize);
    // other CRUD methods omitted for brevity
}

Global Interceptor

For requests that need a custom

source

header, implement

SourceInterceptor

that implements

GlobalInterceptor

:

@Component
public class SourceInterceptor implements GlobalInterceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request newReq = request.newBuilder()
            .addHeader("source", "retrofit")
            .build();
        return chain.proceed(newReq);
    }
}

Configuration

Logging

Retrofit supports four logging strategies. To enable full body logging, set the following in

application.yml

:

retrofit:
  global-log:
    enable: true
    log-level: info
    log-strategy: body

Timeouts

Adjust global timeouts as needed:

retrofit:
  global-timeout:
    connect-timeout-ms: 3000
    read-timeout-ms: 3000
    write-timeout-ms: 35000
    call-timeout-ms: 0

Retry

Enable automatic retry with custom rules:

retrofit:
  global-retry:
    enable: true
    interval-ms: 100
    max-retries: 2
    retry-rules:
      - response_status_not_2xx
      - occur_exception

Conclusion

Retrofit provides a clean, annotation‑driven way to perform HTTP calls in Spring Boot, eliminating the boilerplate required by traditional utilities. Combined with the

retrofit-spring-boot-starter

, it supports advanced features such as micro‑service calls, circuit breaking, and global interceptors.

References

Official starter repository: https://github.com/LianjiaTech/retrofit-spring-boot-starter

JavaMicroservicesbackend developmentSpring BootRetrofitHTTP client
macrozheng
Written by

macrozheng

Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.

0 followers
Reader feedback

How this landed with the community

login 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.