【问题标题】:apache http client: request does not get redirectedapache http客户端:请求没有被重定向
【发布时间】: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 的回答。

标签: java http


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多