《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("http://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();
}

原创文章,转载请注明: 转载自并发编程网 – ifeve.com本文链接地址: 《HttpClient官方文档》1.7. Redirect handling 翻译

  • Trackback 关闭
  • 评论 (0)
  1. 暂无评论

return top