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

标签 httpclient apache-httpclient-4.x

我正在使用 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());
}

当我使用后转发策略时,此代码运行良好,但当我使用重定向时会引发异常。
org.apache.http.client.HttpResponseException: Found

我想要的是获取重定向页面的内容。任何想法都值得赞赏,提前致谢。

最佳答案

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

关于httpclient - 如何通过 httpClient fluent 处理重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18256423/

相关文章:

c# - 错误请求 400 从 API 补丁方法返回

java - Apache Http 客户端和负载平衡器

java - LG G3 手机的 Android 6.0 HTTPClient 问题

java - 尝试在 HTTPCLIENT -JAVA 中发送 POST 请求时,收到 400 Bad Request

java - 使用 Apache HTTP 客户端将 Tomcat Web 应用程序的 keystore 放在哪里

asp.net-mvc - 当前上下文中不存在“HttpClientFactory”

c# - 确定缓存是否用于特定 HttpClient 请求的方法

java - 未发送位置 header 时从http响应获取URL

java - 通过 HttpClient 进行 SPNEGO 身份验证

java - EntityUtils.toString() 中的间歇性死锁