如何通过httpClient fluent处理重定向?

4

我正在使用HttpClient流畅的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策略时,这段代码可以正常工作。但是当我使用redirect时,会抛出异常。

org.apache.http.client.HttpResponseException: Found

我想要的是获取重定向页面的内容。非常感谢您的任何建议。
2个回答

7

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 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,你的代码运行良好。谢谢你的回复,我对你提到的人类干预很好奇。当我手动提交表单时,页面会自动重定向,似乎我什么也不需要做。那么这里的人类干预是什么呢? - Yugang Zhou
@Hippoom:请查看更新。人工干预可能会以 UI 对话框的形式出现,其中包含“确认”/“取消”选项。 - ok2c
@Hippoom:浏览器的黑暗和错误方式是。你必须寻求HTTP规范的智慧。[对不起,我只是忍不住了] - ok2c
看起来像是某个名言的变体? - Yugang Zhou
为了避免在版本4.3.1中遇到的弃用警告,请使用HttpClientBuilder而不是调用DefaultHttpClient构造函数:HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); - RobertG
显示剩余2条评论

2

这是针对 Apache 的更新版本:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接