#android #networking #retrofit #retrofit2 #okhttp
Вопрос:
Я реализовал свой клиент ohttp следующим образом в своем приложении:
fun getOkhttpClient(): OkHttpClient { val chuckerCollector = ChuckerCollector( context = MyApplication.appInstance!!, // Toggles visibility of the push notification showNotification = BuildConfig.DEBUG, // Allows to customize the retention period of collected data retentionPeriod = RetentionManager.Period.ONE_WEEK ) // Create the Interceptor val chuckerInterceptor = ChuckerInterceptor.Builder(MyApplication.appInstance!!) // The previously created Collector .collector(chuckerCollector) // The max body content length in bytes, after this responses will be truncated. .maxContentLength(250_000L) .alwaysReadResponseBody(BuildConfig.DEBUG) .build() val executorService: ExecutorService = ThreadPoolExecutor(20, 20, 1, TimeUnit.HOURS, LinkedBlockingQueue()) val myDispatcher = Dispatcher(executorService) return OkHttpClient.Builder() .connectTimeout(15000, TimeUnit.MILLISECONDS) .retryOnConnectionFailure(true) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .protocols(listOf(Protocol.HTTP_1_1)) .addInterceptor(HeaderInterceptor()) .addInterceptor(chuckerInterceptor) .dispatcher(myDispatcher) .apply { if (BuildConfig.DEBUG) { val logging = HttpLoggingInterceptor() logging.setLevel(HttpLoggingInterceptor.Level.BODY) addInterceptor(logging) } } .build() }
Откройте приложение в первый раз, все работает нормально. Поместите приложение в фоновый режим примерно на 30-40 минут и вернитесь к приложению. Вызовите любой api, и он выдаст —
Несмертельное исключение: java.net.Исключение UnknownHostException Не удается разрешить хост «host_url»: Нет адреса, связанного с именем хоста java.net.Inet6AddressImpl.lookupHostByName (Inet6AddressImpl.java:157) java.net.Inet6AddressImpl.lookupAllHostAddr (Inet6AddressImpl.java:105) java.net.InetAddress.getAllByName (InetAddress.java:1154) okhttp3.Dns$Компаньон$DnsSystem.поиск (Dns.java:5) okhttp3.внутреннее.соединение.RouteSelector.resetnextinetsocket адрес (RouteSelector.java:133). http3.внутреннее.соединение.RouteSelector.nextProxy (RouteSelector.java:20) okhttp3.внутреннее.соединение.RouteSelector.далее (RouteSelector.java:17) okhttp3.внутреннее.соединение.ExchangeFinder.findConnection (искатель обмена.java:196) okhttp3.внутреннее.соединение.Искатель обмена.Найдите соединение (ExchangeFinder.java) okhttp3.внутреннее.соединение.ExchangeFinder.найти (ExchangeFinder.java:47) okhttp3.внутреннее.соединение.RealCall.initExchange$okhttp (RealCall.java:31) okhttp3.внутреннее.соединение.ConnectInterceptor.перехватить (ConnectInterceptor.java:11) okhttp3.внутренний.http.RealInterceptorChain.продолжить (RealInterceptorChain.java:166) okhttp3.внутренний.кэш.CacheInterceptor.перехватить (CacheInterceptor.java:191) okhttp3.внутренний.http.RealInterceptorChain.продолжить (RealInterceptorChain.java:166) okhttp3.внутренний.http.BridgeInterceptor.перехватить (BridgeInterceptor.java:167) okhttp3.внутренний.http.RealInterceptorChain.продолжить (RealInterceptorChain.java:166) okhttp3.внутренний.http.RetryAndFollowUpInterceptor.перехватить (RetryAndFollowUpInterceptor.java:34) okhttp3.внутренний.http.RealInterceptorChain.продолжить (RealInterceptorChain.java:166) com.chuckerteam.chucker.api.ChuckerInterceptor.перехватить (ChuckerInterceptor.java:9) okhttp3.внутренний.http.цепочка реальных восприятий.продолжить (цепочка реальных восприятий.java:166) com.фармасентинель.медицина.модернизация.HeaderInterceptor.перехватить (HeaderInterceptor.java:37) okhttp3.internal.http.RealInterceptorChain.продолжайте (RealInterceptorChain.java:166) okhttp3.internal.соединение.RealCall.getResponseWithInterceptorChain$okhttp (RealCall.java:113). внутреннее подключение.RealCall$AsyncCall.run (RealCall.java:51) java.util.одновременно.Потоковый редактор. runWorker (потоковый редактор.java:1167) java.util.concurrent.ThreadPoolExecutor$Рабочий.запуск (ThreadPoolExecutor.java:641) java.lang.Thread.run (поток.java:764)
Вызвано ошибкой android.system.GaiException android_getaddrinfo: EAI_NODATA (без адреса, связанного с именем хоста) libcore.io.Linux.android_getaddr. (Linux.java) libcore.io.BlockGuardOs.android_getaddr. (BlockGuardOs.java:172) java.net.Inet6AddressImpl.lookupHostByName (Inet6AddressImpl.java:137) java.net.Inet6AddressImpl.lookupAllHostAddr (Inet6AddressImpl.java:105) java.net.InetAddress.getAllByName (InetAddress.java:1154) okhttp3.Dns$Компаньон$DnsSystem.поиск (Dns.java:5) okhttp3.внутреннее.соединение.RouteSelector.resetnextinetsocket адрес (RouteSelector.java:133). http3.внутреннее.соединение.RouteSelector.nextProxy (RouteSelector.java:20) okhttp3.внутреннее.соединение.RouteSelector.далее (RouteSelector.java:17) okhttp3.внутреннее.соединение.ExchangeFinder.findConnection (ExchangeFinder.java:196) okhttp3.внутреннее.соединение.Искатель обмена.Найдите соединение (ExchangeFinder.java) okhttp3.внутреннее.соединение.ExchangeFinder.найти (ExchangeFinder.java:47) okhttp3.внутреннее.соединение.RealCall.initExchange$okhttp (RealCall.java:31) okhttp3.внутреннее.соединение.ConnectInterceptor.перехватить (ConnectInterceptor.java:11) okhttp3.внутренний.http.RealInterceptorChain.продолжить (RealInterceptorChain.java:166) okhttp3.внутренний.кэш.CacheInterceptor.перехватить (CacheInterceptor.java:191) okhttp3.внутренний. http.RealInterceptorChain.продолжить (RealInterceptorChain.java:166) okhttp3.внутренний.http.BridgeInterceptor.перехватить (BridgeInterceptor.java:167) okhttp3.внутренний.http.RealInterceptorChain.продолжить (RealInterceptorChain.java:166) okhttp3.внутренний.http.RetryAndFollowUpInterceptor.перехватить (RetryAndFollowUpInterceptor.java:34) okhttp3.внутренний.http.RealInterceptorChain.продолжить (RealInterceptorChain.java:166) com.chuckerteam.chucker.api.ChuckerInterceptor.перехват (ChuckerInterceptor.java:9) okhttp3.внутренняя.http.цепочка realinterceptor.продолжайте (RealInterceptorChain.java:166) com.фармасентинель.медицина.модернизация.HeaderInterceptor.перехватить (HeaderInterceptor.java:37) okhttp3.внутренний.http.RealInterceptorChain.продолжить (RealInterceptorChain.java:166) okhttp3.внутреннее.соединение.RealCall.getResponseWithInterceptorChain$okhttp (RealCall.java:113). внутреннее подключение.RealCall$AsyncCall.run (RealCall.java:51) java.util.одновременно.Потоковый редактор. runWorker (потоковый редактор.java:1167) java.util.concurrent.ThreadPoolExecutor$Рабочий.запуск (ThreadPoolExecutor.java:641) java.lang.Thread.run (поток.java:764)
Который я регистрирую из своего перехватчика с помощью try catch.
Откройте любое другое приложение, и они будут работать нормально. Выключите приложение и перезагрузите его, чтобы решить проблему, а иногда переключение между Wi-Fi и сотовой связью также решает ее.
Комментарии:
1.
Unable to resolve host "host_url"
— это буквально то, что есть в ошибке, или вы отредактировали сообщение об ошибке, чтобы скрыть реальный URL-адрес? Кроме того, если вы упростите своюOkHttpClient.Builder
конфигурацию (например, удалите Чакер), исчезнет ли проблема?2. на данный момент я скрываю URL-адрес. И это происходило до добавления чакера.