Skip to content

Configured RequestConfig in HttpClient gets overwritten by default [SPR-12540] #17144

Closed
@spring-projects-issues

Description

@spring-projects-issues

Jean-Pierre Bergamin opened SPR-12540 and commented

HttpComponentsClientHttpRequestFactory.createRequest always sets the HttpClientContext.REQUEST_CONFIG attribute of the HttpContext - also with a default config if none can be found.

The HttpClientBuilder on the other hand allows to set a default RequestConfig with:

RequestConfig requestConfig = RequestConfig.custom()
        .setCookieSpec(NO_SPEC_PROVIDER)
        .build();

 HttpClient httpClient = HttpClientBuilder.create().
        ....
        setDefaultRequestConfig(requestConfig).
        ...		
        build();

The returned InternalHttpClient by the builder later sets this configured default requestConfig if no other request config has been set:

private void setupContext(final HttpClientContext context) {
    ....
    if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
        context.setAttribute(HttpClientContext.REQUEST_CONFIG, this.defaultConfig);
    }
}

But since a default RequestConfig has been set in HttpComponentsClientHttpRequestFactory.createRequest, it is not applied here and the configured RequestConfig in the HttpClientBuilder is not used.

As a workaround you have to create your own HttpComponentsClientHttpRequestFactory implementation and overwrite createHttpContext to return a configured HttpContext like:

public class StatefullHttpComponentsClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory
{
    private final HttpContext httpContext;

    public StatefullHttpComponentsClientHttpRequestFactory(HttpClient httpClient, HttpContext httpContext)
    {
        super(httpClient);
        this.httpContext = httpContext;
    }

    @Override
    protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri)
    {
        return this.httpContext;
    }
}

HttpContext context = new BasicHttpContext();
context.setAttribute(HttpClientContext.REQUEST_CONFIG, requestConfig);

ClientHttpRequestFactory requestFactory = new ContextAwareHttpComponentsClientHttpRequestFactory(httpClient, context));

RestOperations restClient = new RestTemplate(requestFactory);

Conclusion: Do not set a default RequestConfig in HttpComponentsClientHttpRequestFactory if the http client is of instance InternalHttpClient and therefore configured by the HttpClientBuilder.


Issue Links:

Referenced from: commits 71783c5, 5236eb6

1 votes, 7 watchers

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions