Follow 302 redirect using Spring restTemplate?

Using the default ClientHttpRequestFactory implementation – which is the SimpleClientHttpRequestFactory – the default behaviour is to follow the URL of the location header (for responses with status codes 3xx) – but only if the initial request was a GETrequest.

Details can be found in this class – searching for the following method:

protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {

    ...

    if ("GET".equals(httpMethod)) {
        connection.setInstanceFollowRedirects(true);
    }

Here the relevant doc comment of HttpURLConnection.setInstanceFollowRedirects method:

Sets whether HTTP redirects (requests with response code 3xx) should
be automatically followed by this {@code HttpURLConnection}
instance.

The default value comes from followRedirects, which defaults to true.

Leave a Comment