java - Apache http 客户端 : request does not get redirected

标签 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 状态码?

最佳答案

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

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

关于java - Apache http 客户端 : request does not get redirected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58241991/

相关文章:

java - 获取执行 JDBC Insert/Update/Delete 后使用的表名

java - 如何通过 HibernateTemplate 更新数据库中的特定字段

java - 如何在 Spring MVC 中创建主 Controller

c - 使用 Arduino 和 HTTP 填写网络表单

http - HTTP 是什么样的?

java - 无法将大于 1.5 MB 的文件添加到存储库

java - 注释可以获取上下文对象吗?

sockets - 如何将 HTTPS 流量从 SOCKS 代理转发到 HTTP 代理

http - 在 GO 中使用 # 解析 url

javascript - 在等待 Promise 时切换 AngularJS View