阅读306 返回首页    go 阿里云 go 技术社区[云栖]


《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();
}

转载自 并发编程网 - ifeve.com

最后更新:2017-05-19 14:04:52

  上一篇:go  《云数据管理:挑战与机遇》2.3.3 恢复和提交
  下一篇:go  Nature | 干细胞图片数据库共享,深度学习预测细胞外观