问题
I'm using the fluent API of HttpClient to make a GET request:
String jsonResult = Request.Get(requestUrl)
.connectTimeout(2000)
.socketTimeout(2000)
.execute().returnContent().asString();
But for each request I get the following warning:
apr 07, 2016 12:26:46 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies
WARNING: Invalid cookie header: "Set-Cookie: WMF-Last-Access=07-Apr-2016;Path=/;HttpOnly;Expires=Mon, 09 May 2016 00:00:00 GMT". Invalid 'expires' attribute: Mon, 09 May 2016 00:00:00 GMT
How can I fix this and keep using the fluent interface? Ideally I'd want a proper way to fix it, but since I don't really care about the cookies in my use case any solution that just allows me to stop displaying the warnings (besides redirecting stderr, cause I need that) is welcome.
回答1:
The default HttpClient has difficulty understanding the latest RFC-compliant headers.
Instead of hiding the warning, just switch to a standard cookie spec like this (HttpClient 4.4+):
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
回答2:
If you want to use HttpClientBuilder
you can use the following sytax:
HttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build()).build();
回答3:
For the developers don't want to think on the object model, wrapping the HttpClient for a RestTemplate might be used as below ( as @comiventor mentioned above especially for Spring Boot Developers).
a Customizer for RestTemplate,
public class RestTemplateStandardCookieCustomizer
implements RestTemplateCustomizer {
@Override
public void customize(final RestTemplate restTemplate) {
final HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();
restTemplate.setRequestFactory(
new HttpComponentsClientHttpRequestFactory(httpClient)
);
}
}
and using it with the RestTemplate Builder
var restTemplate = restTemplateBuilder.additionalCustomizers(
new RestTemplateStandardCookieCustomizer()
).build();
回答4:
Solved with:
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.client.protocol.ResponseProcessCookies", "fatal");
来源:https://stackoverflow.com/questions/36473478/fixing-httpclient-warning-invalid-expires-attribute-using-fluent-api