4

我正在使用 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

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

4

2 回答 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();
于 2013-08-16T10:36:25.893 回答
2

这是针对 apache 的更新版本:

CloseableHttpClient httpClient = 
  HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
.build();
于 2015-04-13T13:57:52.613 回答