如何防止apache http客户端跟随重定向

Chr*_*ris 41 java apache-httpclient-4.x

我正在使用apache http客户端连接到远程服务器.远程服务器发送重定向,我想实现我的客户端不自动跟随重定向,以便我可以提取propper标头并做我想要的目标.

我正在寻找一个简单的工作代码示例(复制粘贴),停止自动重定向跟随行为.

我发现防止HttpClient 4跟随重定向,但似乎我太愚蠢了用HttpClient 4.0(GA)实现它

Chr*_*ris 49

由于macbirdie,魔术是:

params.setParameter("http.protocol.handle-redirects",false);
Run Code Online (Sandbox Code Playgroud)

省略了进口,这是一个复制粘贴样本:

HttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();

// HTTP parameters stores header etc.
HttpParams params = new BasicHttpParams();
params.setParameter("http.protocol.handle-redirects",false);

// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();

// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

// connect and receive 
HttpGet httpget = new HttpGet("http://localhost/web/redirect");
httpget.setParams(params);
response = httpclient.execute(httpget, localContext);

// obtain redirect target
Header locationHeader = response.getFirstHeader("location");
if (locationHeader != null) {
    redirectLocation = locationHeader.getValue();
  System.out.println("loaction: " + redirectLocation);
} else {
  // The response is invalid and did not provide the new location for
  // the resource.  Report an error or possibly handle the response
  // like a 404 Not Found error.
}
Run Code Online (Sandbox Code Playgroud)

  • 这是David Riccitelli过时的使用答案 (3认同)

Can*_*ner 24

这对我有用:

HttpGet httpGet = new HttpGet("www.google.com");
HttpParams params = httpGet.getParams();
params.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
httpGet.setParams(params);
Run Code Online (Sandbox Code Playgroud)

  • 完美地为我工作,只需要很少的代码更改.谢谢. (3认同)
  • 不推荐使用(httpGet.getParams())(4.3)使用{@link org.apache.http.client.config.RequestConfig} (2认同)

Dav*_*lli 24

使用HttpClient 4.3和Fluent:

final String url = "http://...";
final HttpClient client = HttpClientBuilder.create()
    .disableRedirectHandling()
    .build();
final Executor executor = Executor.newInstance(client);
final HttpResponse response = executor.execute(Request.Get(url))
    .returnResponse();
Run Code Online (Sandbox Code Playgroud)

  • 想要做与@FanJin完全相同的事情。有人可以提供他问题的答案吗? (2认同)

mac*_*die 17

默认HttpClient实现在可配置性方面非常有限,但您可以使用HttpClient的布尔参数来控制重定向处理http.protocol.handle-redirects.

请参阅文档以供参考.

  • 一个简单的例子[可以在这里找到](http://www.baeldung.com/httpclient-stop-follow-redirect) (2认同)

小智 13

而不是直接使用该属性,您可以使用:

final HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, false);
Run Code Online (Sandbox Code Playgroud)

  • `HttpClientParams` @deprecated (4.3) 使用 {@link org.apache.http.client.config.RequestConfig} (2认同)