I need to get the redirect URL from an API call using retrofit. If I'm testing the url with Postman
it gives back the Header and I can see the URL in it. This is how I build my retrofit:
private static Interceptor interceptor = chain -> {
okhttp3.Response response = chain.proceed(chain.request());
Log.d("REDIRECT","to"+response.header("Location"));
return response;
};
public static NetworkInterface getNetworkInterface() {
if (networkInterface == null) {
serverGson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setLenient()
.create();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.followRedirects(true)
.addInterceptor(interceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(serverGson))
.baseUrl(BASE_URL)
.build();
networkInterface = retrofit.create(NetworkInterface.class);
}
return networkInterface;
}
And this my API call:
Disposable api = Server.getNetworkInterface().oAuthUser("param",
"param","param",
"param","param")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(response-> {
if (response.isSuccessful()) {
String responseHeader = response.headers().toString();
Log.d("auth header",responseHeader);
}
}, error-> {
error.printStackTrace();
});
This what I get back:
2019-03-29 14:55:35.935 22434-22434/com.package.app W/System.err: java.net.ConnectException: Failed to connect to BASEURL/IP ADDRESS
It's okay because the second URL where I should be redirected it's not pointing anywhere so if I call it I should get back this. But for the fist time I call the valid URL and postman gives back 302 Found
so I think when retrofit get back this trying to call the URL but it does not work so I get back this error message.
The problem is that in the error case I should see the second URL where I should be redirected and not the first URL. How can I get the second URL in the onFailure case?