Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the response URL from Retrofit?

I'm using Retrofit for REST web services my android project. It works fine overall untill the point I'm trying to read several parameters from the return URL. For exapmle on the web browser:

  1. type "http://foobar.com/"
  2. Hit enter
  3. it becomes "http://foobar2.com/abc=123"

Now the question is how do I get that "abc=123" value from retrofit response. Thanks heaps!

like image 619
WenChao Avatar asked Jul 28 '15 04:07

WenChao


People also ask

What is retrofit HTTP client?

Retrofit is a type-safe REST client for Android, Java and Kotlin developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp.


2 Answers

I have solve the problem.Here is my solution:

Define a request

@GET 
Call<String> getSend(@Url String url);

and send

Api.get(WXApi.class).getSend(ip).enqueue(new Callback<String>() {

    @Override
    public void onResponse(Call<String> call, Response<String> response) {

        Log.d(TAG,"response.raw().request().url();"+response.raw().request().url());}

    @Override
    public void onFailure(Call<String> call, Throwable t) {

    }
});
like image 113
suntiago Avatar answered Sep 23 '22 15:09

suntiago


Below is my way: (using retrofit2)

  • First: Create an instance of Interceptor:

    public class LoggingInterceptor implements Interceptor {
    
    private String requestUrl;
    
    public String getRequestUrl() {
        return requestUrl;
    }
    
    public void setRequestUrl(String requestUrl) {
        this.requestUrl = requestUrl;
    }
    
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        setRequestUrl(response.request().url().toString());
        return response;
    
    }
    }
    
  • Add Interceptor to retrofit

    Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    retrofit.client().interceptors().add(new LoggingInterceptor());
    
  • Get url from onResponse() method

    @Override
    public void onResponse(Response<T> response, Retrofit retrofit) {
        List<Interceptor> data = retrofit.client().interceptors();
        if (data != null && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i) instanceof LoggingInterceptor) {
                    LoggingInterceptor intercept = (LoggingInterceptor) data.get(i);
                    String url = intercept.getRequestUrl();
                    // todo : do what's ever you want with url
                    break;
                } else {
                    continue;
                }
            }
        }
    
    }
    
like image 35
ThaiPD Avatar answered Sep 21 '22 15:09

ThaiPD