【问题标题】:Retrofit get a parameter from a redirect URL改造从重定向 URL 获取参数
【发布时间】:2014-09-17 15:49:55
【问题描述】:

我正在使用改造。

我有一个重定向到另一个端点的端点。后者(我最终到达的端点)在其 URL 中有一个我需要的参数。获取此参数值的最佳方法是什么?

我什至不知道如何使用 Retrofit 获取重定向到的 URL。

【问题讨论】:

  • 遇到同样的问题,还有更新吗?
  • @WenChao 我会使用 OkHttp 网络拦截器来获取结果响应并获取其 url。
  • 更新了这个问题的答案。

标签: java android networking retrofit


【解决方案1】:

OkHttp 的响应将为您提供线路级请求 (https://square.github.io/okhttp/3.x/okhttp/okhttp3/Response.html#request--)。这将是从重定向发起响应的请求。 Request 会给你它的 HttpUrl,HttpUrl 可以给你它的参数的键和值、路径等。

使用 Retrofit 2,只需使用 retrofit2.Response.raw() 获取 okhttp3.Response 并按照上述操作。

【讨论】:

    【解决方案2】:

    我正在使用改造。我可以通过这种方式获取重定向网址:

    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;
    }
    

    希望它可以帮助某人。

    【讨论】:

      【解决方案3】:

      解决方案是使用拦截器,例如

      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;
          }
      };
      

      将拦截器添加到您的 HttpClient 并将其添加到 Retrofit(本示例使用 2.0)

      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();
      }
      

      现在您可以完全访问整个重定向历史记录。

      【讨论】:

      • 完整访问整个重定向历史的代码是什么?
      • 可能更完整的答案:stackoverflow.com/questions/31667230/…
      • locationHistory 在我的例子中是一个 List,但很容易成为 List。另一个答案与 Android 有关,我的是通用 Java
      • “locationHistory”部分指的是什么?
      猜你喜欢
      • 2016-03-26
      • 2013-02-24
      • 2021-11-09
      • 2015-04-27
      • 2012-01-18
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      • 2014-09-05
      相关资源
      最近更新 更多