Skip to content

Commit 4f65ba4

Browse files
committed
Simplify creation of HttpContext for Apache HttpClient
Closes gh-25066
1 parent 23a66e0 commit 4f65ba4

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

spring-web/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequestFactory.java

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2020 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@
1919
import java.io.Closeable;
2020
import java.io.IOException;
2121
import java.net.URI;
22+
import java.util.function.BiFunction;
2223

2324
import org.apache.http.client.HttpClient;
2425
import org.apache.http.client.config.RequestConfig;
@@ -66,6 +67,9 @@ public class HttpComponentsClientHttpRequestFactory implements ClientHttpRequest
6667

6768
private boolean bufferRequestBody = true;
6869

70+
@Nullable
71+
private BiFunction<HttpMethod, URI, HttpContext> httpContextFactory;
72+
6973

7074
/**
7175
* Create a new instance of the {@code HttpComponentsClientHttpRequestFactory}
@@ -157,6 +161,19 @@ public void setBufferRequestBody(boolean bufferRequestBody) {
157161
this.bufferRequestBody = bufferRequestBody;
158162
}
159163

164+
/**
165+
* Configure a factory to pre-create the {@link HttpContext} for each request.
166+
* <p>This may be useful for example in mutual TLS authentication where a
167+
* different {@code RestTemplate} for each client certificate such that
168+
* all calls made through a given {@code RestTemplate} instance as associated
169+
* for the same client identity. {@link HttpClientContext#setUserToken(Object)}
170+
* can be used to specify a fixed user token for all requests.
171+
* @param httpContextFactory the context factory to use
172+
* @since 5.2.7
173+
*/
174+
public void setHttpContextFactory(BiFunction<HttpMethod, URI, HttpContext> httpContextFactory) {
175+
this.httpContextFactory = httpContextFactory;
176+
}
160177

161178
@Override
162179
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
@@ -296,7 +313,7 @@ protected void postProcessHttpRequest(HttpUriRequest request) {
296313
*/
297314
@Nullable
298315
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
299-
return null;
316+
return (this.httpContextFactory != null ? this.httpContextFactory.apply(httpMethod, uri) : null);
300317
}
301318

302319

0 commit comments

Comments
 (0)