apache http client:请求未重定向

时间:2019-10-04 19:09:22

标签: java http

我需要检查以下情况:访问URL时,应将其重定向到新URL,curl很好:

curl -i http://localhost:8080/index.html
HTTP/1.1 302 Found
Date: Fri, 04 Oct 2019 18:57:07 GMT
Location: http://localhost:8080/
Content-Length: 0

我得到了预期的302状态代码。但是,当我尝试使用Java中的apache http客户端运行此命令时,却收到状态代码200。 Java代码:

HttpGet request = new HttpGet("http://localhost:8080/index.html");
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
System.out.println("Completed executing the request, status: " + response.getStatusLine());
Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);

如何在JAVA中也获取302状态代码?

1 个答案:

答案 0 :(得分:1)

您需要禁用重定向。试试这个:

HttpParams params = new BasicHttpParams();
params.setParameter("http.protocol.handle-redirects",false);
HttpGet request = new HttpGet("http://localhost:8080/index.html");
request.setParams(params);