知识点

相关文章

更多

最近更新

更多

HttpClient 重定向处理

2019-04-09 23:00|来源: 网路

HttpClient自动处理所有类型的重定向,除了HTTP规范明确禁止的那些重定向需要用户干预。 请参阅其他(状态码303)在POST上重定向,并且按照HTTP规范的要求将PUT请求转换为GET请求。 可以使用自定义重定向策略来放宽由HTTP规范施加的对POST方法的自动重定向的限制。 在下面的教程中,我们将使用LaxRedirectStrategy来处理http重定向。

Maven依赖关系

我们使用maven来管理依赖关系,并使用Apache HttpClient 4.5版本。 将以下依赖项添加到您的项目中。

pom.xml 文件的内容如下 -

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yiibai.httpclient.httmethods</groupId>
    <artifactId>http-get</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <url>https://memorynotfound.com</url>
    <name>httpclient - ${project.artifactId}</name>

    <dependencies>
        <!-- Apache Commons IO -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


重定向处理示例

在下面的例子中,我们对资源 http://httpbin.org/redirect/3 进行 HTTP GET。 此资源重新导向到另一个资源x次。可以使用URIUtils.resolve(httpGet.getURI(), target, redirectLocations)来获取最终的Http位置。

文件:HttpClientRedirectHandlingExample.java -

import org.apache.http.HttpHost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

/**
 * This example demonstrates the use of {@link HttpGet} request method.
 * and handling redirect strategy with {@link LaxRedirectStrategy}
 */
public class HttpClientRedirectHandlingExample {

    public static void main(String... args) throws IOException, URISyntaxException {

        CloseableHttpClient httpclient = HttpClients.custom()
                .setRedirectStrategy(new LaxRedirectStrategy())
                .build();

        try {
            HttpClientContext context = HttpClientContext.create();
            HttpGet httpGet = new HttpGet("http://httpbin.org/redirect/3");
            System.out.println("Executing request " + httpGet.getRequestLine());
            System.out.println("----------------------------------------");

            httpclient.execute(httpGet, context);
            HttpHost target = context.getTargetHost();
            List<URI> redirectLocations = context.getRedirectLocations();
            URI location = URIUtils.resolve(httpGet.getURI(), target, redirectLocations);
            System.out.println("Final HTTP location: " + location.toASCIIString());

        } finally {
            httpclient.close();
        }
    }
}


执行上面示例代码,得到以下结果 -

Executing request GET http://httpbin.org/redirect/3 HTTP/1.1
----------------------------------------
Final HTTP location: http://httpbin.org/get


相关问答

更多
  • HttpClient的默认行为符合HTTP规范(RFC 2616)的要求, 10.3.3 302 Found ... If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, sinc ...
  • 返回代码200表示的请求成功,并正常的返回交易结果。 举例: public static String post(String uri, String contentType, String content) throws Exception { org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); PostMethod post = new PostMethod(u ...
  • 这将是当前的URL,您可以通过调用获得 HttpGet#getURI(); 编辑:你没有提到你如何做重定向 这对我们有用,因为我们处理了302。 听起来你正在使用DefaultRedirectHandler。 我们曾经这样做 获取当前URL是一件棘手的事情。 你需要使用自己的上下文。 以下是相关的代码段, HttpGet httpget = new HttpGet(url); HttpContext context = new BasicHttpContext(); ...
  • 我终于使用loopj http客户端解决了这个问题 I finally solved this using loopj http client
  • 这意味着给定的站点处于DDOS保护模式(也许你试图经常打开它?)解决方法你需要停止那么多(例如在尝试之间等待一段时间)。 或者,如果你坚持使用一些javascript执行库(Rhino?),它将执行cloudflare正在使用的javascript。 It means that given site is under DDOS protection mode (maybe you try to open it too often?) to workaround you would need to stop ...
  • 默认的HttpClientHandler使用相同的HttpWebRequest基础结构。 不是将NetworkCredential分配给Credentials属性,而是创建CredentialCache并分配它。 这就是我使用的代替AutoRedirect和一些async / await仙尘,它可能会更漂亮,更可靠。 public class GlobalRedirectHandler : DelegatingHandler { protected override Task
  • 你得到了正确的答案,你只是没有正确打印它。 那是因为你是entity上的EntityUtils.toString()而不是httpEntity 。 这里 HttpEntity httpEntity = response.getEntity(); String str = ""; if (httpEntity != null) { str = EntityUtils.toString(entity); System.out.println(str); } 你传递的entity是 UrlEnc ...
  • HTTP规范要求实体封闭方法(如POST和PUT)仅在人为干预后重定向。 HttpClient默认遵守此要求。 。 10.3 Redirection 3xx This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. The action required MAY be carried out by ...
  • 来自RFC 2616 : 如果收到302状态代码以响应GET或HEAD以外的请求,则用户代理不得自动重定向请求,除非用户可以确认,因为这可能会改变发出请求的条件。 你确定你的服务器没有使用' POST,redirect,GET '这个成语吗? 您可以在Apache HTTP客户端中禁用重定向的自动跟踪 。 例如: _httpClient = new DefaultHttpClient(); _httpClient.getParams().setParameter( ClientPNames.HAND ...
  • HttpClient未正确重定向的原因是因为该站点将您重定向到HTTPS然后再返回到HTTP。 快速解决方法是改为https://medivia.wikispaces.com/Monsters ,无论如何这是一个更好的主意: HttpResponseMessage response = await _httpClient.GetAsync("https://medivia.wikispaces.com/Monsters"); // Works fine! :) 我很好奇为什么它第一种方式不起作用,所以我挖 ...