Retrofit 2.x.x + Okhttp3 intercepter + Dagger + Rx - 连接未关闭

时间:2017-09-21 18:04:49

标签: android retrofit2 dagger-2 rx-android okhttp3

我正在使用 改造2.2.0 + okhttp3 Intercepter + GSONConverterFactory(Dagger2)+ RxJava2。

在检查服务器时,似乎应用程序建立的连接保持活动状态,即使收到响应后也不会关闭。

基本上我有

应用程序模块 - 存在使用GSONCOnverterFactory和okhttp客户端及其拦截器进行改造的地方。

App Module类:

@Singleton
@Provides
protected MyService providesMyService(@Named("MyService") Retrofit retrofit) {
    return retrofit.create(MyService.class);
}

@Singleton
@Provides
@Named("MyService")
protected Retrofit providesMyRetrofit(GsonConverterFactory factory) {

    OkHttpClient.Builder builder = new OkHttpClient.Builder();

    builder.connectTimeout(3000, TimeUnit.MILLISECONDS);
    builder.readTimeout(3000, TimeUnit.MILLISECONDS);

    builder.addInterceptor(new MyInterceptor());
    builder.addNetworkInterceptor(new CachingControlInterceptor());

    //caching 
    builder.cache(MyCache.getCache());

    builder.addInterceptor(new HttpLoggingInterceptor()
            .setLevel(loggingLevel));
    try {
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(builder.build())
                .addConverterFactory(factory)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

    } catch (Exception e) {

    }
}

我的拦截器:

@Override
public Response intercept(Chain chain) throws IOException {
    final Charset UTF8 = Charset.forName("UTF-8");
    final String userPassword = USERNAME + ":" + PASSWORD;

    Request original = chain.request();
    Request request = original.newBuilder()
            .header("User-Agent", SOME_AGENT)

            .header("Authorization", "Basic " + new String(Base64.encodeBase64(userPassword.getBytes(UTF8)), UTF8))
            .header("Content-Type", "application/json; charset=utf-8")
            .header("Keep-Alive", "timeout = 3")
            .method(original.method(), original.body())
            .build();


    Response response = chain.proceed(request);


    return response;
}

这是Rx代码:

 MyApp.getInstance().getAppComponent()
            .getMyService()
            .getData(queryMap, resultValues)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe((MyResponse myResponse) -> {

               //success result handled here
            }, throwable -> {
                //exception result handled here
            });

我在代码或logcat中看不到任何警告。传递Keep-Alive:标头中的超时也没有帮助。

我如何从应用程序端验证连接是否正确关闭,或者即使在应用程序收到响应后仍保持打开状态?

0 个答案:

没有答案