Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle redirect by httpClient fluent?

I'm writing acceptance tests with HttpClient fluent api and have some trouble.

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

This code works well when I use post-forward strategy, but an exception is thrown when I use redirect instead.

org.apache.http.client.HttpResponseException: Found

What I want is getting the content of the redirected page. Any idea is appreciate, thanks in advance.

like image 617
Yugang Zhou Avatar asked Jan 13 '23 15:01

Yugang Zhou


2 Answers

The HTTP specification requires entity enclosing methods such as POST and PUT be redirected after human intervention only. HttpClient honors this requirement by default. .

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.

One can use a custom redirect strategy to relax restrictions on automatic redirection if necessary.

    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();
like image 50
ok2c Avatar answered Jan 18 '23 20:01

ok2c


This is for an updated version of apache:

CloseableHttpClient httpClient = 
  HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
.build();
like image 31
thouliha Avatar answered Jan 18 '23 18:01

thouliha