Skip to content

Instantly share code, notes, and snippets.

@swankjesse
Created April 29, 2020 03:20
Show Gist options
  • Save swankjesse/80135f4e03629527e723ab3bcf64be0b to your computer and use it in GitHub Desktop.
Save swankjesse/80135f4e03629527e723ab3bcf64be0b to your computer and use it in GitHub Desktop.
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Response;
import static okhttp3.internal.http.StatusLine.HTTP_PERM_REDIRECT;
import static okhttp3.internal.http.StatusLine.HTTP_TEMP_REDIRECT;
/**
* In OkHttp 4.5 and earlier, HTTP 307 and 308 redirects were only honored if the request method
* was GET or HEAD.
*
* In OkHttp 4.6 and later, HTTP 307 and 308 redirects are honored for all request methods.
*
* If you're upgrading to OkHttp 4.6 and would like to retain the previous behavior, install this
* as a **network interceptor**. It will strip the `Location` header of impacted responses to
* prevent the redirect.
*
* <pre>{@code
*
* OkHttpClient client = client.newBuilder()
* .addNetworkInterceptor(new LegacyRedirectInterceptor())
* .build();
*
* }</pre>
*/
class LegacyRedirectInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
int code = response.code();
if (code != HTTP_TEMP_REDIRECT && code != HTTP_PERM_REDIRECT) return response;
String method = response.request().method();
if (method.equals("GET") || method.equals("HEAD")) return response;
String location = response.header("Location");
if (location == null) return response;
return response.newBuilder()
.removeHeader("Location")
.header("LegacyRedirectInterceptor-Location", location)
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment