HttpGet标头是否会覆盖httpClient标头(Apache HttpClient)?

时间:2015-07-31 06:46:16

标签: httpclient apache-httpclient-4.x

我想在HttpClient中设置标头,因为我希望我的大多数服务调用都有默认标头。

RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(ApacheHttpClient.DEFAULT_CONNECTION_TIMEOUT)
            .setSocketTimeout(ApacheHttpClient.DEFAULT_SOCKET_TIMEOUT).build();

    httpClient = HttpClients.custom().setDefaultHeaders(getDefaultHeaderList()).setDefaultRequestConfig(requestConfig).setRetryHandler(new RetryHandler()).build();

但是,如果需要,我想替换默认标头。我将它设置为HttpGet标题。

int cTimeout = (connTimeout == null) ? DEFAULT_CONNECTION_TIMEOUT : connTimeout;
    int sTimeout = (socketTimeout == null) ? DEFAULT_SOCKET_TIMEOUT : socketTimeout;
    httpGet.setConfig(RequestConfig.custom().setConnectTimeout(cTimeout).setSocketTimeout(sTimeout).build());

HttpGet标头是否会覆盖HttpClient设置的标头?

1 个答案:

答案 0 :(得分:1)

调试请求,在org.apache.http.impl.client.InternalHttpClient.doExecute(HttpHost, HttpRequest, HttpContext)我可以看到保存超时的配置首先从请求中获取,如果未设置,则使用默认值:

  RequestConfig config = null;
        if (request instanceof Configurable) {
            config = ((Configurable) request).getConfig();
        }
        if (config == null) {
            final HttpParams params = request.getParams();
            if (params instanceof HttpParamsNames) {
                if (!((HttpParamsNames) params).getNames().isEmpty()) {
                    config = HttpClientParamConfig.getRequestConfig(params);
                }
            } else {
                config = HttpClientParamConfig.getRequestConfig(params);
            }
        }
        if (config != null) {
            localcontext.setRequestConfig(config);
        }
        setupContext(localcontext);