HttpClient自动处理所有类型的重定向,除了HTTP规范明确禁止的那些重定向需要用户干预。 请参阅其他(状态码303)在POST上重定向,并且按照HTTP规范的要求将PUT请求转换为GET请求。 可以使用自定义重定向策略来放宽由HTTP规范施加的对POST方法的自动重定向的限制。 在下面的教程中,我们将使用LaxRedirectStrategy来处理http重定向。
Maven依赖关系
我们使用maven来管理依赖关系,并使用Apache HttpClient 4.5版本。 将以下依赖项添加到您的项目中。
pom.xml 文件的内容如下 -
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.yiibai.httpclient.httmethods
http-get
1.0.0-SNAPSHOT
https://memorynotfound.com
httpclient - ${project.artifactId}
org.apache.httpcomponents
httpclient
4.5.2
maven-compiler-plugin
3.5.1
1.8
1.8
重定向处理示例
在下面的例子中,我们对资源 http://httpbin.org/redirect/3 进行 HTTP GET。 此资源重新导向到另一个资源x次。可以使用URIUtils.resolve(httpGet.getURI(), target, redirectLocations)来获取最终的Http位置。
文件:HttpClientRedirectHandlingExample.java -
package com.yiibai.httpdemo;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
/**
* This example demonstrates the use of {@link HttpGet} request method.
* and handling redirect strategy with {@link LaxRedirectStrategy}
*/
public class HttpClientRedirectHandlingExample {
public static void main(String... args) throws IOException, URISyntaxException {
CloseableHttpClient httpclient = HttpClients.custom()
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
try {
HttpClientContext context = HttpClientContext.create();
HttpGet httpGet = new HttpGet("http://httpbin.org/redirect/3");
System.out.println("Executing request " + httpGet.getRequestLine());
System.out.println("----------------------------------------");
httpclient.execute(httpGet, context);
HttpHost target = context.getTargetHost();
List redirectLocations = context.getRedirectLocations();
URI location = URIUtils.resolve(httpGet.getURI(), target, redirectLocations);
System.out.println("Final HTTP location: " + location.toASCIIString());
} finally {
httpclient.close();
}
}
}
执行上面示例代码,得到以下结果 -
Executing request GET http://httpbin.org/redirect/3 HTTP/1.1
----------------------------------------
Final HTTP location: http://httpbin.org/get
¥ 我要打赏
纠错/补充
收藏
加QQ群啦,易百教程官方技术学习群
注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。
本教程展示了如何使用Apache HttpClient 4.5处理HTTP重定向。通过添加LaxRedirectStrategy,可以自动处理包括POST方法在内的重定向。示例代码执行了一个GET请求,该请求被重定向3次,最终输出了最终的HTTP位置。
9823

被折叠的 条评论
为什么被折叠?



