【问题标题】:How to handle redirect by httpClient fluent?如何通过 httpClient fluent 处理重定向?
【发布时间】:2013-08-15 15:47:16
【问题描述】:

我正在使用 HttpClient fluent api 编写验收测试,但遇到了一些麻烦。

@When("^I submit delivery address and delivery time$")
public void I_submit_delivery_address_and_delivery_time() throws Throwable {

    Response response = Request
            .Post("http://localhost:9999/food2go/booking/placeOrder")
            .bodyForm(
                    param("deliveryAddressStreet1",
                            deliveryAddress.getStreet1()),
                    param("deliveryAddressStreet2",
                            deliveryAddress.getStreet2()),
                    param("deliveryTime", deliveryTime)).execute();
    content = response.returnContent();
    log.debug(content.toString());
}

当我使用 post-forward 策略时,这段代码运行良好,但是当我使用重定向时抛出异常。

org.apache.http.client.HttpResponseException: Found

我想要的是获得重定向页面的内容。任何想法都非常感谢,在此先感谢。

【问题讨论】:

    标签: httpclient apache-httpclient-4.x


    【解决方案1】:

    HTTP specification 要求仅在人工干预后重定向 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 the user agent without interaction
       with the user if and only if the method used in the second request is
       GET or HEAD. 
    

    ...

       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, since this might
       change the conditions under which the request was issued.
    

    如有必要,可以使用自定义重定向策略来放松对自动重定向的限制。

        DefaultHttpClient client = new DefaultHttpClient();
        client.setRedirectStrategy(new LaxRedirectStrategy());
        Executor exec = Executor.newInstance(client);
        String s = exec.execute(Request
                .Post("http://localhost:9999/food2go/booking/placeOrder")
                .bodyForm(...)).returnContent().asString();
    

    【讨论】:

    • +1,您的代码运行良好。感谢您的回复,我很好奇您提到的人工干预,当我在浏览器上手动提交表单时,页面自动重定向,似乎我不需要做任何事情。那么这里的人为干预是什么?
    • @Hippoom:查看更新。人为干预可能采用带有“确认”/“取消”选项的 UI 对话框形式
    • 对不起,我还是很困惑,我是新手。我尝试了几种浏览器(chrome,firefox,ie),它们都自动重定向。他们是否为了方便而为用户提供干预(我认为为用户点击确认或取消很烦人)?
    • @Hippoom:浏览器的黑暗和错误的方式是。您必须在 HTTP 规范中寻求智慧。 [我很抱歉。我就是忍不住]
    • :) 看起来像是一句名言的变体?
    【解决方案2】:

    这是 apache 的更新版本:

    CloseableHttpClient httpClient = 
      HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
    .build();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      相关资源
      最近更新 更多