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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1519392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:45:26  来源:igfitidea点击:

How to prevent apache http client from following a redirect

javaapache-httpclient-4.x

提问by Chris

I'm connecting to a remote server with apache http client. the remote server sends a redirect, and i want to achieve that my client isn't following the redirect automatically so that i can extract the propper header and do whatever i want with the target.

我正在使用 apache http 客户端连接到远程服务器。远程服务器发送重定向,我想实现我的客户端不会自动跟随重定向,以便我可以提取正确的标头并对目标执行任何我想做的事情。

i'm looking for a simple working code sample(copy paste) that stops the automatic redirect following behaviour.

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

i found Preventing HttpClient 4 from following redirect, but it seems i'm too stupid to implement it with HttpClient 4.0 (GA)

我发现阻止 HttpClient 4 跟随重定向,但似乎我太愚蠢了,无法使用 HttpClient 4.0 (GA)

采纳答案by macbirdie

The default HttpClientimplementation is pretty limited in configurability, but you can control the redirect handling by using HttpClient's boolean parameter http.protocol.handle-redirects.

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

See the docsfor reference.

请参阅文档以供参考。

回答by Chris

The magic, thanks to macbirdie , is:

感谢macbirdie 的神奇之处在于:

params.setParameter("http.protocol.handle-redirects",false);

Imports are left out, here's a copy paste sample:

导入被排除在外,这是一个复制粘贴示例:

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.
}

回答by David Koski

Rather than use the property directly you can use:

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

final HttpParams params = new BasicHttpParams();
HttpClientParams.setRedirecting(params, false);

回答by Caner

This worked for me:

这对我有用:

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

回答by user769733

GetMethod method = new GetMethod(url);
method.setFollowRedirects(false); 

回答by Simple-Solution

To avoid automatic redirection header, one must first configure the request to not do automatic redirects. You can do this by calling HttPClientParams.setRedirectionand set it to false. Code snippet is shown below:

为避免自动重定向标头,必须首先将请求配置为不进行自动重定向。您可以通过调用HttPClientParams.setRedirection并将其设置为false. 代码片段如下所示:

HttpPost postURL = new HttpPost(resourceURL);
...
HttpClientParams.setRedirecting(postURL.getParams(), false);

回答by David Riccitelli

Using HttpClient 4.3 and Fluent:

使用 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();

回答by liuck8080

instead of call HttpClientBuilder directly, you can use

而不是直接调用 HttpClientBuilder,你可以使用

HttpClients.custom().disableRedirectHandling().build();

回答by Fan Jin

Before HttpClient 4.3

在 HttpClient 4.3 之前

In older versions of the Http Client (before 4.3), we can configure what the client does with redirects as follows:

在旧版本的 Http Client(4.3 之前)中,我们可以配置客户端如何使用重定向,如下所示:

@Test
public void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() 
  throws ClientProtocolException, IOException {
    DefaultHttpClient instance = new DefaultHttpClient();

    HttpParams params = new BasicHttpParams();
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    // HttpClientParams.setRedirecting(params, false); // alternative

    HttpGet httpGet = new HttpGet("http:/testabc.com");
    httpGet.setParams(params);
    CloseableHttpResponse response = instance.execute(httpGet);

    assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
}

Notice the alternative API that can be used to configure the redirect behavior without using setting the actual raw http.protocol.handle-redirects parameter:

请注意可用于配置重定向行为的替代 API,而无需设置实际的原始 http.protocol.handle-redirects 参数:

HttpClientParams.setRedirecting(params, false);

Also notice that, with follow redirects disabled, we can now check that the Http Response status code is indeed 301 Moved Permanently – as it should be.

还要注意的是,在禁用跟随重定向的情况下,我们现在可以检查 Http 响应状态代码是否确实是 301 Moved Permanently——它应该是这样。

After HttpClient 4.3

在 HttpClient 4.3 之后

HttpClient 4.3 introduced a cleaner, more high level APIto build and configure the client:

HttpClient 4.3 引入了一个更简洁、更高级的 API来构建和配置客户端:

@Test
public void givenRedirectsAreDisabled_whenConsumingUrlWhichRedirects_thenNotRedirected() 
  throws ClientProtocolException, IOException {
    HttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build();
    HttpResponse response = instance.execute(new HttpGet("http://testabc.com"));

    assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
}

Note that the new API configures the entire client with this redirect behavior – not just the individual request. Reference: http://www.baeldung.com/httpclient-stop-follow-redirect

请注意,新 API 使用此重定向行为配置整个客户端——而不仅仅是单个请求。参考:http: //www.baeldung.com/httpclient-stop-follow-redirect

回答by Pravin

this worked for me CloseableHttpClient client = HttpClientBuilder.create().disableRedirectHandling().build();

这对我有用 CloseableHttpClient client = HttpClientBuilder.create().disableRedirectHandling().build();