Sub topic 3
Choosing a Request Factory and Setting Timeouts
Assume Java 17+, Spring Boot 3.2+, basic dependency injection, and HTTP fundamentals. A ClientHttpRequestFactory is the component that creates the underlying HTTP requests. Choose one when you need transport-specific behavior, such as timeouts.
A connect timeout limits how long connection setup may take. A read timeout limits how long the client waits for response data.
import java.net.http.HttpClient;
import java.time.Duration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
@Configuration
class HttpClientConfig {
@Bean
RestClient apiClient(RestClient.Builder builder) {
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.build();
JdkClientHttpRequestFactory factory =
new JdkClientHttpRequestFactory(httpClient);
factory.setReadTimeout(Duration.ofSeconds(5));
return builder
.baseUrl("https://api.example.com")
.requestFactory(factory)
.build();
}
}The JDK factory is a practical default. Other factories can use Apache HttpClient or another transport when you need connection pooling or library-specific features.
Interceptors and Shared Customization
A request interceptor runs before each request. Use it for cross-cutting behavior such as authentication, tracing, or consistent headers.
RestClient client(RestClient.Builder builder, String token) {
return builder
.baseUrl("https://api.example.com")
.requestInterceptor((request, body, execution) -> {
request.getHeaders().setBearerAuth(token);
return execution.execute(request, body);
})
.build();
}Keep interceptors small. Do not hide business decisions or retry loops inside them.
Declarative Clients with HTTP Interfaces
An HTTP interface describes endpoints as Java methods. HttpServiceProxyFactory creates an implementation backed by RestClient.
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.service.annotation.GetExchange;
interface TodoApi {
@GetExchange("/todos/{id}")
Todo findById(@PathVariable long id);
}Create the proxy with RestClientAdapter. This style reduces repetitive request-building code while keeping the API contract visible.
Testing Client Code
MockRestServiceServer intercepts requests before they reach the network. Bind it to the builder before building the client, then assert the request and provide a response.
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
RestClient client = builder.build();
server.expect(requestTo("https://api.example.com/todos/1"))
.andRespond(withSuccess(
"{\"id\":1,\"title\":\"Write docs\",\"completed\":false}",
MediaType.APPLICATION_JSON));
Todo todo = client.get()
.uri("/todos/{id}", 1)
.retrieve()
.body(Todo.class);
server.verify();Low-Level Access with `exchange()`
Use exchange() when retrieve() is too restrictive. Its callback receives the request and response, allowing custom status handling, headers, or body parsing.
Todo todo = client.get()
.uri("/todos/{id}", 1)
.exchange((request, response) -> {
if (response.getStatusCode().is2xxSuccessful()) {
return objectMapper.readValue(response.getBody(), Todo.class);
}
throw new IllegalStateException("Unexpected status: "
+ response.getStatusCode());
});Exercise
Which timeout prevents an application from waiting forever for response data?
Show answer
The read timeout. The connect timeout only limits connection setup.