There are two ways to control redirects in this version of HttpClient. The first way to control redirects is simply by specifying the maximum number of redirects, the HttpClient is allowed to perform.

using CodeScales.Http;
using CodeScales.Http.Entity;
using CodeScales.Http.Methods;

HttpClient httpClient = new HttpClient();
httpClient.SetMaxRedirects(0);
HttpGet httpGet = new HttpGet(new Uri("http://www.codescales.com/home"));
HttpResponse httpResponse = httpClient.Execute(httpGet);

Console.WriteLine("Response Code: " + httpResponse.ResponseCode);
Console.WriteLine("Response Content: " + EntityUtils.ToString(httpResponse.Entity));

In this example we have set the maximum number of redirects to zero. this means that the HttpClient might receive a 302 or 301 status code from the server, but it will not send another request to the new Location of the resource. The same way we could have limited the number of redirects to two: this would have resulted in the HttpClient receiving a 302/301 status code from the server, with a new Location, and then automatically issuing another GET request to the new Location. The response object that is returned, will reflect the last response received. You can see the new Location received using the following API:


Console.WriteLine("Response Code: " + httpResponse.Location);

The second way to control redirects is by using the HttpBehavior class.

This time we will create an “HttpBehavior” class to control the redirects. We will tell it exactly what are steps we expect the HttpClient to perform. Then when we execute the GetMethod (line 12), we pass the HttpBehavior object to the HttpClient as a parameter, and the HttpClient will make sure every request and response cycle matches exactly the behavior we expect.

using CodeScales.Http;
using CodeScales.Http.Entity;
using CodeScales.Http.Methods;

HttpClient httpClient = new HttpClient();
HttpGet httpGet = new HttpGet(new Uri("http://www.codescales.com/home"));

HttpBehavior httpBehavior = new HttpBehavior();
httpBehavior.AddStep(301, "http://www.codescales.com");
httpBehavior.AddStep(200);

HttpResponse httpResponse = httpClient.Execute(httpGet, httpBehavior);

Console.WriteLine("Response Code: " + httpResponse.ResponseCode);
Console.WriteLine("Response Code: " + httpResponse.Location);
Console.WriteLine("Response Content: " + EntityUtils.ToString(httpResponse.Entity));

This example will send a GET request to “http://www.codescales.com/home”, and it will expect to receive a 301 response with “http://www.codescales.com” as the new location. Then it will send another GET request to the new location, and it will expect the response to have a 200 status code.
Any deviation from this behavior will result in an HttpBehaviorException thrown.