侧边栏壁纸
博主头像
Terry

『LESSON 5』

  • 累计撰写 90 篇文章
  • 累计创建 21 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

OkHttp重定向处理

Terry
2020-09-12 / 0 评论 / 0 点赞 / 870 阅读 / 1,910 字 / 正在检测是否收录...

简述

OkHttp是个很方便的HTTP-CLIENT,就算是返回重定向,OkHttp也自动帮我们处理,不需要我们自己判断处理。但是如果需求是需要你重定向一次,我们该如何处理?接下来我来讲下OkHttp多次重定向原理和怎样设置自行处理重定向。

重定向

客户端向服务器发起一个请求时,会获得对应的资源,服务器接收到请求后,发现请求的这个资源实际放在另外一个位置,服务器则会在返回的响应头Location字段保存请求资源的正确URL,并且设置response的状态码为30x。

状态码

状态码 作用
300 Multiple Choices针对请求,服务器可执行多种操作。 服务器可根据请求者 (user agent) 选择一项操作,或提供操作列表供请求者选择。
301 Moved Permanently请求的网页已永久移动到新位置。 服务器返回此响应(对 GET 或 HEAD 请求的响应)时,会自动将请求者转到新位置。
302 Move Temporarily 服务器目前从不同位置的网页响应请求,但请求者应继续使用原有位置来进行以后的请求。
303 See Other请求者应当对不同的位置使用单独的 GET 请求来检索响应时,服务器返回此代码。
304 Not Modified自从上次请求后,请求的网页未修改过。 服务器返回此响应时,不会返回网页内容。
305 Use Proxy请求者只能使用代理访问请求的网页。 如果服务器返回此响应,还表示请求者应使用代理。
306 Switch Proxy在最新版的规范中,306状态码已经不再被使用。
307 Temporary Redirect服务器目前从不同位置的网页响应请求,但请求者应继续使用原有位置来进行以后的请求。

OkHttpp中的实现

首先定位到RetryAndFollowUpInterceptor类。该类主要是个拦截器,处理重定向

/**
 * This interceptor recovers from failures and follows redirects as necessary. It may throw an
 * {@link IOException} if the call was canceled.
 */
public final class RetryAndFollowUpInterceptor implements Interceptor {
  /**
   * How many redirects and auth challenges should we attempt? Chrome follows 21 redirects; Firefox,
   * curl, and wget follow 20; Safari follows 16; and HTTP/1.0 recommends 5.
   * 最大重定向次数
   */
  private static final int MAX_FOLLOW_UPS = 20;

  private final OkHttpClient client;

  public RetryAndFollowUpInterceptor(OkHttpClient client) {
    this.client = client;
  }

  @Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Transmitter transmitter = realChain.transmitter();

    int followUpCount = 0;
    Response priorResponse = null;
    // 循环处理重定向
    while (true) {
      // 省略
      // 具体是这里处理重定向,我们重点看followUpRequest代码
      Request followUp = followUpRequest(response, route);

      if (followUp == null) {
        if (exchange != null && exchange.isDuplex()) {
          transmitter.timeoutEarlyExit();
        }
        return response;
      }

      RequestBody followUpBody = followUp.body();
      if (followUpBody != null && followUpBody.isOneShot()) {
        return response;
      }

      closeQuietly(response.body());
      if (transmitter.hasExchange()) {
        exchange.detachWithViolence();
      }
      // 处理次数大于MAX_FOLLOW_UPS,则抛出异常
      if (++followUpCount > MAX_FOLLOW_UPS) {
        throw new ProtocolException("Too many follow-up requests: " + followUpCount);
      }

      request = followUp;
      priorResponse = response;
    }
  }

followUpRequest

 /**
   * Figures out the HTTP request to make in response to receiving {@code userResponse}. This will
   * either add authentication headers, follow redirects or handle a client request timeout. If a
   * follow-up is either unnecessary or not applicable, this returns null.
   */
  private Request followUpRequest(Response userResponse, @Nullable Route route) throws IOException {
    if (userResponse == null) throw new IllegalStateException();
    int responseCode = userResponse.code();

    final String method = userResponse.request().method();
    switch (responseCode) {
      case HTTP_PROXY_AUTH:
        Proxy selectedProxy = route != null
            ? route.proxy()
            : client.proxy();
        if (selectedProxy.type() != Proxy.Type.HTTP) {
          throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
        }
        return client.proxyAuthenticator().authenticate(route, userResponse);

      case HTTP_UNAUTHORIZED:
        return client.authenticator().authenticate(route, userResponse);

      case HTTP_PERM_REDIRECT:
      case HTTP_TEMP_REDIRECT:
        // "If the 307 or 308 status code is received in response to a request other than GET
        // or HEAD, the user agent MUST NOT automatically redirect the request"
        if (!method.equals("GET") && !method.equals("HEAD")) {
          return null;
        }
        // fall-through
      // 状态码为300、301、302、303处理
      case HTTP_MULT_CHOICE:
      case HTTP_MOVED_PERM:
      case HTTP_MOVED_TEMP:
      case HTTP_SEE_OTHER:
        // Does the client allow redirects?
        // 如果client配置不允许重定向,直接返回
        if (!client.followRedirects()) return null;
        // 否则拿到header的Location信息返回
        String location = userResponse.header("Location");
        if (location == null) return null;
        HttpUrl url = userResponse.request().url().resolve(location);

        // Don't follow redirects to unsupported protocols.
        if (url == null) return null;

        // If configured, don't follow redirects between SSL and non-SSL.
        boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
        if (!sameScheme && !client.followSslRedirects()) return null;

        // Most redirects don't include a request body.
        Request.Builder requestBuilder = userResponse.request().newBuilder();
        if (HttpMethod.permitsRequestBody(method)) {
          final boolean maintainBody = HttpMethod.redirectsWithBody(method);
          if (HttpMethod.redirectsToGet(method)) {
            requestBuilder.method("GET", null);
          } else {
            RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
            requestBuilder.method(method, requestBody);
          }
          if (!maintainBody) {
            requestBuilder.removeHeader("Transfer-Encoding");
            requestBuilder.removeHeader("Content-Length");
            requestBuilder.removeHeader("Content-Type");
          }
        }

        // When redirecting across hosts, drop all authentication headers. This
        // is potentially annoying to the application layer since they have no
        // way to retain them.
        if (!sameConnection(userResponse.request().url(), url)) {
          requestBuilder.removeHeader("Authorization");
        }

        return requestBuilder.url(url).build();

      case HTTP_CLIENT_TIMEOUT:
        // 408's are rare in practice, but some servers like HAProxy use this response code. The
        // spec says that we may repeat the request without modifications. Modern browsers also
        // repeat the request (even non-idempotent ones.)
        if (!client.retryOnConnectionFailure()) {
          // The application layer has directed us not to retry the request.
          return null;
        }

        RequestBody requestBody = userResponse.request().body();
        if (requestBody != null && requestBody.isOneShot()) {
          return null;
        }

        if (userResponse.priorResponse() != null
            && userResponse.priorResponse().code() == HTTP_CLIENT_TIMEOUT) {
          // We attempted to retry and got another timeout. Give up.
          return null;
        }

        if (retryAfter(userResponse, 0) > 0) {
          return null;
        }

        return userResponse.request();

      case HTTP_UNAVAILABLE:
        if (userResponse.priorResponse() != null
            && userResponse.priorResponse().code() == HTTP_UNAVAILABLE) {
          // We attempted to retry and got another timeout. Give up.
          return null;
        }

        if (retryAfter(userResponse, Integer.MAX_VALUE) == 0) {
          // specifically received an instruction to retry without delay
          return userResponse.request();
        }

        return null;

      default:
        return null;
    }
  }

具体是300/301/302/303的判断,直接从响应header中Location获取重定向的地址

代码

public class BaseHttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(BaseHttpUtils.class);

    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
            .followRedirects(false)
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS)
            .build();

    /**
     * 获取真实链接
     *
     * @param url url
     * @return 真实链接
     */
    public static String getRealUrl(final String url) {
        return getRealUrl(url, null, null);
    }

    /**
     * 获取真实链接
     *
     * @param url     url
     * @param headers 头信息
     * @return 真实链接
     */
    public static String getRealUrl(final String url, final Map<String, String> headers) {
        return getRealUrl(url, null, headers);
    }

    /**
     * 获取真实链接
     *
     * @param url    url
     * @param params 参数
     * @return 真实链接
     */
    public static String getRealUrlWithParams(final String url, final Map<String, String> params) {
        return getRealUrl(url, params, null);
    }

    /**
     * 获取真实链接<br/>
     * 仅仅只是follow上一次重定向前,如果follow的url之前还有重定向的话此处不标准
     *
     * @param url     url
     * @param params  参数
     * @param headers 头信息
     * @return 真实链接
     */
    public static String getRealUrl(final String url, final Map<String, String> params, final Map<String, String> headers) {
        HttpUrl urlParse = HttpUrl.parse(url);
        if (urlParse == null) {
            return url;
        }
        if (params != null && params.size() > 0) {
            HttpUrl.Builder builder = urlParse.newBuilder();
            params.forEach(builder::addQueryParameter);
            urlParse = builder.build();
        }
        Builder urlBuilder = new Builder().url(urlParse);
        if (headers != null && headers.size() > 0) {
            urlBuilder.headers(Headers.of(headers));
        }
        try (Response response = HTTP_CLIENT.newCall(urlBuilder.build()).execute()) {
            int code = response.code();
            if (code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_MOVED_TEMP) {
                String location = response.header("Location");
                if (location != null) {
                    // 判断location中的URL格式是否正确
                    HttpUrl httpUrl = response.request().url().resolve(location);
                    // 如果不为空则正确,为空直接返回url并记录日志
                    if (httpUrl != null) {
                        return location;
                    }
                    logger.warn("url格式不正确,url为:" + location);
                }
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return url;
    }

}

以上代码是我公司需求,只需对url进行一次重定向处理,如果http返回的状态码为301/302,直接返回重定向url

总结

OkHttp很方便,不需要你对每次相应做判断,如果是重定向需要获取Location再次请求,RetryAndFollowUpInterceptor拦截器帮我们做了处理。但是因为公司需求,我这边只需重定向一次,如果按照OkHttp的方式,会进行网络I/O处理,造成资源浪费。在OkHttpClient中设置followRedirects(false),就能取消OkHttp帮我们对重定向处理,然后我们可以根据自己需求自行处理。

0

评论区