How to get the response URL from Retrofit?

前端 未结 6 851
感情败类
感情败类 2021-01-05 15:48

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

6条回答
  •  离开以前
    2021-01-05 16:27

    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 response, Retrofit retrofit) {
          List 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;
                  }
              }
          }
      
      }
      

提交回复
热议问题