OkHttp3在拦截器中动态改变schema,host等

最近在写wanandroid app,之前登录和注册接口是http请求,今天登录app发现无法登录了.

去www.wanandroid.com看了下,原来是鸿洋大神登录和注册接口改成了https了,
那么怎么优雅处理这个问题呢

当然是在拦截器中处理了

这是登录和注册接口

  /**
     * 登陆
     * http://www.wanandroid.com/user/login
     *
     * @param username user name
     * @param password password
     * @return 登陆数据
     */
    @POST("user/login")
    @FormUrlEncoded
    Observable> getLoginData(@Field("username") String username, @Field("password") String password);

    /**
     * 注册
     * http://www.wanandroid.com/user/register
     *
     * @param username user name
     * @param password password
     * @param repassword re password
     * @return 注册数据
     */
    @POST("user/register")
    @FormUrlEncoded
    Observable> getRegisterData(@Field("username") String username, @Field("password") String password, @Field("repassword") String repassword);

处理之后是这个样子滴

   OkHttpClient provideClient(OkHttpClient.Builder builder) {
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
            builder.addInterceptor(loggingInterceptor);
            builder.addNetworkInterceptor(new StethoInterceptor());
        }
        File  cacheFile = new File(Constants.PATH_CACHE);
        Cache cache     = new Cache(cacheFile, 1024 * 1024 * 50);
        Interceptor cacheInterceptor = chain -> {
            Request request = chain.request();
            if (!CommonUtils.isNetworkConnected()) {
                request = request.newBuilder()
                                 .cacheControl(CacheControl.FORCE_CACHE)
                                 .build();
            }
          //看这里,开始处理了
          //处理的当url是login或者regist接口时,将schema设置成https
            String url = request.url().toString();
            if (url.endsWith("user/login") || url.endsWith("user/register")) {
                HttpUrl httpUrl = request.url()
                                         .newBuilder()
                                         .scheme("https")
                                         .host("www.wanandroid.com")
                                         .build();
                request = request.newBuilder()
                                 .url(httpUrl)
                                 .build();
            }
            //处理结束了,完美搞定
            Response response = chain.proceed(request);
            if (CommonUtils.isNetworkConnected()) {
                int maxAge = 0;
                // 有网络时, 不缓存, 最大保存时长为0
                response.newBuilder()
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .removeHeader("Pragma")
                        .build();
            } else {
                // 无网络时,设置超时为4周
                int maxStale = 60 * 60 * 24 * 28;
                response.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .removeHeader("Pragma")
                        .build();
            }
            return response;
        };
        X509TrustManager x509TrustManager = initX509TrustManager();
        SSLSocketFactory sslSocketFactory = null;
        try {
            sslSocketFactory = initSSLFactory(x509TrustManager);

        //设置缓存
        builder.addNetworkInterceptor(cacheInterceptor);
        builder.addInterceptor(cacheInterceptor);
        builder.cache(cache);
        //设置超时
        builder.connectTimeout(10, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        //错误重连
        builder.retryOnConnectionFailure(true);
        //cookie认证
        builder.cookieJar(new PersistentCookieJar(new SetCookieCache(),
                new SharedPrefsCookiePersistor(WanAndroidApp.getInstance())));
        builder.sslSocketFactory(sslSocketFactory,x509TrustManager);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return builder.build();
    }

   //这里默认让所有https请求通行,并没有做其他校验
    private SSLSocketFactory initSSLFactory(X509TrustManager trustManager) throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[]{trustManager}, new SecureRandom());
        return sslContext.getSocketFactory();
    }

    private X509TrustManager initX509TrustManager() {
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
        return trustManager;
    }

你可能感兴趣的:(OkHttp3在拦截器中动态改变schema,host等)