《HttpClient官方文檔》1.7. Redirect handling 翻譯
1.7. 重定向處理
HttpClient能夠處理所有類型的自動重定向,除了被那些需要用戶幹預被HTTP規範明確禁止的。考慮到根據HTTP規範中其他被轉為GET請求的POST和PUT請求的重定向(狀態碼303),可以使用一個自定義的重定向策略來降低HTTP規範強製規定的POST方法自動重定向的限製。
LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();
CloseableHttpClient httpclient = HttpClients.custom()
.setRedirectStrategy(redirectStrategy)
.build();
HttpClient在其執行過程中不得不重寫請求消息。默認地,HTTP/1.0、HTTP/1.1通常使用相對請求URIs。同樣,原始請求可以被重定向到其他位置。 最終解釋的HTTP位置由原始的請求和上下文構建。用公共方法URIUtils#resolve構建生成最終請求的解釋絕對URI。該方法包括重定向請求或原始請求中的末尾標識片段。
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpClientContext context = HttpClientContext.create();
HttpGet httpget = new HttpGet("https://localhost:8080/");
CloseableHttpResponse response = httpclient.execute(httpget, context);
try {
HttpHost target = context.getTargetHost();
List<URI> redirectLocations = context.getRedirectLocations();
URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
System.out.println("Final HTTP location: " + location.toASCIIString());
// Expected to be an absolute URI
} finally {
response.close();
}
最後更新:2017-05-19 14:04:52