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.

+4


source to share


3 answers


OkHttp's answer will give you an explorer-level request ( https://square.github.io/okhttp/3.x/okhttp/okhttp3/Response.html#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.

+3


source


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.

+1


source


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

private Interceptor interceptor = new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        okhttp3.Response response = chain.proceed(chain.request());
        locationHistory.add(response.header("Location"));
        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();
    client.followRedirects(true);
    client.addNetworkInterceptor(interceptor);
    OkHttpClient httpClient = client.build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient)
            .build();
}

      

You now have full access to the call forwarding history.

+1


source







All Articles