Retrofit gets parameter from redirect url

I am using Retrofit.

I have an endpoint that is redirecting to a different endpoint. The last one (the endpoint I end at) has a parameter in its url that I need. What is the best way to get the value of this parameter?

I can't even figure out how to get the url I'm redirected to using Retrofit.


source to share

3 answers

OkHttp's answer will give you an explorer-level request ( ). This will be the request that triggered the response from the redirect. The request will give you the HttpUrl, and the HttpUrl can provide you with the keys and parameter values, paths, etc.

With Retrofit 2, just use retrofit2.Response.raw () to get okhttp3.Response and follow the above.



I am using modification. And I can get the redirect url like this:

private boolean handleRedirectUrl(RetrofitError cause) {
    if (cause != null && cause.getResponse() != null) {
        List<Header> headers = cause.getResponse().getHeaders();
        for (Header header : headers) {
             //KEY_HEADER_REDIRECT_LOCATION = "Location"
            if (KEY_HEADER_REDIRECT_LOCATION.equals(header.getName())) {
                String redirectUrl = header.getValue();

                return true;

    return false;


Hope this can help someone.



A solution for this would be to use an interceptor for example.

private Interceptor interceptor = new Interceptor() {
    public okhttp3.Response intercept(Chain chain) throws IOException {
        okhttp3.Response response = chain.proceed(chain.request());
        return response;


Add an interceptor to your HttpClient and add it for refitting (using example 2.0 for this example)

public void request(String url) {
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    OkHttpClient httpClient =;

    Retrofit retrofit = new Retrofit.Builder()


You now have full access to the call forwarding history.



All Articles