Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit get a parameter from a redirect URL

I am using Retrofit.

I have an endpoint that redirects to another endpoint. The latter (the endpoint that I end up at) has a parameter in its URL that I need. What is the best way to get the value of this parameter?

I cannot even figure out how to get the URL that I am redirected to, using Retrofit.

like image 293
Eric Cochran Avatar asked Sep 17 '14 15:09

Eric Cochran


2 Answers

OkHttp's Response will give you the wire-level request (https://square.github.io/okhttp/3.x/okhttp/okhttp3/Response.html#request--). This will be the Request that initiated the Response from the redirect. The Request will give you its HttpUrl, and HttpUrl can give you its parameters' keys and values, paths, etc.

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

like image 195
Eric Cochran Avatar answered Sep 20 '22 11:09

Eric Cochran


I am using retrofit. And I can get the redirect url following this way :

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 it could help someone.

like image 20
gZerone Avatar answered Sep 19 '22 11:09

gZerone