OkHttp3永不超时互联网上的超时 [英] OkHttp3 Never Timeout on slow internet

查看:1383
本文介绍了OkHttp3永不超时互联网上的超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我已经阅读了很多关于我的问题的问题,但是它从来没有给我解决方案.这是我阅读的有关我的问题的一些问题.

First of all, I have read so many questions regarding my question but it never gives me the solution. Here are some of the questions which I read regarding my question.

  • Question 1
  • Question 2
  • Qusetion 3
  • Question 4
  • Question 5
  • Question 6
  • Question 7

我还阅读了此文章关于我的问题,但它也从未为我提供解决方案.

I also read this article regarding my question but it also never provide me the solution.

问题:

我在Web服务应用程序中使用Okhhtp3库.它工作正常,但是当互联网连接速度慢或连接不可靠时,它就被卡住了,永远不会超时,也永远不会调用超时异常或失败方法.

I am using Okhhtp3 library in my application for Web Services. It's working fine but when the internet connection slow or unreliable connection it's stuck and never times out or never calls the timeout exception or failure method.

这是客户端代码:

OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .retryOnConnectionFailure(false)
            .build();

如何在20秒后获取超时异常或调用失败方法?

请帮助我.谢谢

推荐答案

正如Trevor Halvorson指出的那样,您可以在客户端构建器中通过以下方式设置callTimeout:

As pointed out by Trevor Halvorson, you could set callTimeout during client builder, in this way:

OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .callTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .retryOnConnectionFailure(false)
            .build();

我已经使用okhttp33.14.0版本在一个虚拟项目中进行了个人测试:

I've personally tested in a dummy project using version 3.14.0 of okhttp3:

implementation 'com.squareup.okhttp3:okhttp:3.14.0'

并设置5秒钟的超时时间,将我的仿真器连接设置为 GPRS 连接性,我得到

And setting a timout of 5 seconds and my emulator connection to GPRS and Poor connectivity I get

java.net.SocketExcpetion: Socket closed: timeout

这是我完整的虚拟活动:

package com.example.shadowsheep.myapplication;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.TimeUnit;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView helloTextView = findViewById(R.id.helloTextView);

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .callTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .retryOnConnectionFailure(false)
                .build();

        Request request = new Request.Builder()
                .url("https://www.versionestabile.it/blog")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.d("OKHTTP3", e.getMessage());
                // You get this failure
                runOnUiThread(() -> helloTextView.setText("TIMEOUT - FAILURE -> " + e.getMessage()));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    final String _body = response.body().string();
                    Log.d("OKHTTP3", _body);
                    runOnUiThread(() -> {
                        helloTextView.setText(_body);
                    });
                } catch (InterruptedIOException e) {
                    runOnUiThread(() -> {
                        // Or this exception depending when timeout is reached
                        helloTextView.setText("TIMEOUT EXCEPTION->"+ e.getCause() + ": " + e.getMessage());
                    });
                }
            }
        });
    }
}

我还将给我我的应用程序build.gradle文件.

I'll give you also my app build.gradle file.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.shadowsheep.myapplication"
        minSdkVersion 24
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha03'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.2-alpha02'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0-alpha02'

    implementation 'com.squareup.okhttp3:okhttp:3.14.0'
}

这篇关于OkHttp3永不超时互联网上的超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆