【发布时间】:2019-10-05 03:12:49
【问题描述】:
我需要检查这个场景:当我访问一个 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 状态码?
【问题讨论】:
-
我认为您正在从服务器获取 302 重定向,但 http 客户端代码“隐藏”了这一事实,自动遵循重定向,然后返回 location 属性中表示的页面。如果您必须看到重定向,请参阅@bhusak 的回答。