258. Setting the redirect policy

When we try to access a resource that was moved to a different URI, the server will return an HTTP status code in the range of 3xx, as well as information about the new URI. Browsers are capable of automatically sending another request to the new location when they receive a redirect response (301, 302, 303, 307, and 308).

The HTTP Client API can automatically redirect to this new URI if we explicitly set the redirect policy via followRedirects(), as follows:

HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS)
.build();

To never redirect, just give the HttpClient.Redirect.NEVER constant to followRedirects() (this is the default).

To always redirect, except from HTTPS URLs to HTTP URLs, just give the HttpClient.Redirect.NORMAL constant to followRedirects().

When the redirect policy is not set to ALWAYS, the application is responsible for handling redirects. Commonly, this is accomplished by reading the new address from the HTTP Location header, as follows (the following code is only interested in redirecting if the returned status code is 301 (moved permanently) or 308 (permanent redirect)):

int sc = response.statusCode();

if (sc == 301 || sc == 308) { // use an enum for HTTP response codes
String newLocation = response.headers()
.firstValue("Location").orElse("");

// handle the redirection to newLocation
}

A redirect can be easily detected by comparing the request URI with the response URI. If they are not the same, then a redirect occurs:

if (!request.uri().equals(response.uri())) {
System.out.println("The request was redirected to: "
+ response.uri());
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.60.158