Constant Dns.java line 5 errors on crashlytics - android

I have implemented my okhttp client as follows in my app:
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()
}
Open the app for the first time everything works fine.
Put the app in background for about 30 to 40 mins and come back to the app.
Call any api and it will give -
Non-fatal Exception: java.net.UnknownHostException Unable to resolve host "host_url": No address associated with hostname java.net.Inet6AddressImpl.lookupHostByName (Inet6AddressImpl.java:157) java.net.Inet6AddressImpl.lookupAllHostAddr (Inet6AddressImpl.java:105) java.net.InetAddress.getAllByName (InetAddress.java:1154) okhttp3.Dns$Companion$DnsSystem.lookup (Dns.java:5) okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress (RouteSelector.java:133) okhttp3.internal.connection.RouteSelector.nextProxy (RouteSelector.java:20) okhttp3.internal.connection.RouteSelector.next (RouteSelector.java:17) okhttp3.internal.connection.ExchangeFinder.findConnection (ExchangeFinder.java:196) okhttp3.internal.connection.ExchangeFinder.findHealthyConnection (ExchangeFinder.java) okhttp3.internal.connection.ExchangeFinder.find (ExchangeFinder.java:47) okhttp3.internal.connection.RealCall.initExchange$okhttp (RealCall.java:31) okhttp3.internal.connection.ConnectInterceptor.intercept (ConnectInterceptor.java:11) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.java:191) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:167) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:34) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) com.chuckerteam.chucker.api.ChuckerInterceptor.intercept (ChuckerInterceptor.java:9) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) com.pharmasentinel.medsii.retrofit.HeaderInterceptor.intercept (HeaderInterceptor.java:37) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp (RealCall.java:113) okhttp3.internal.connection.RealCall$AsyncCall.run (RealCall.java:51) java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167) java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641) java.lang.Thread.run (Thread.java:764)
Caused by android.system.GaiException android_getaddrinfo failed: EAI_NODATA (No address associated with hostname) libcore.io.Linux.android_getaddrinfo (Linux.java) libcore.io.BlockGuardOs.android_getaddrinfo (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$Companion$DnsSystem.lookup (Dns.java:5) okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress (RouteSelector.java:133) okhttp3.internal.connection.RouteSelector.nextProxy (RouteSelector.java:20) okhttp3.internal.connection.RouteSelector.next (RouteSelector.java:17) okhttp3.internal.connection.ExchangeFinder.findConnection (ExchangeFinder.java:196) okhttp3.internal.connection.ExchangeFinder.findHealthyConnection (ExchangeFinder.java) okhttp3.internal.connection.ExchangeFinder.find (ExchangeFinder.java:47) okhttp3.internal.connection.RealCall.initExchange$okhttp (RealCall.java:31) okhttp3.internal.connection.ConnectInterceptor.intercept (ConnectInterceptor.java:11) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.java:191) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:167) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:34) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) com.chuckerteam.chucker.api.ChuckerInterceptor.intercept (ChuckerInterceptor.java:9) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) com.pharmasentinel.medsii.retrofit.HeaderInterceptor.intercept (HeaderInterceptor.java:37) okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:166) okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp (RealCall.java:113) okhttp3.internal.connection.RealCall$AsyncCall.run (RealCall.java:51) java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167) java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641) java.lang.Thread.run (Thread.java:764)
Which i am logging from my interceptor using try catch.
Open any other app and they work fine.
Kill the app and restart resolves the problem, and sometimes switching between wifi and cellular also solves it.

Related

Fatal Exception: java.net.SocketTimeoutException on Android 10 and above

I'm getting this crash on my app
(Platform.kt line 128
okhttp3.internal.platform.Platform.connectSocket)
Fatal Exception: java.net.SocketTimeoutException failed to connect to
domain/IP (port 443) from /Another IP (port 37062) after 120000ms:
isConnected failed: ETIMEDOUT (Connection timed out)
Crash details on firebase crashlytics
libcore.io.IoBridge.isConnected (IoBridge.java:343)
java.net.Socket.connect (Socket.java:646)
okhttp3.internal.platform.Platform.connectSocket (Platform.kt:128)
okhttp3.internal.connection.ConnectPlan.connectSocket (ConnectPlan.kt:246)
okhttp3.internal.connection.ConnectPlan.connectTcp (ConnectPlan.kt:128)
okhttp3.internal.connection.SequentialExchangeFinder.find (SequentialExchangeFinder.kt:41)
okhttp3.internal.connection.RealCall.initExchange$okhttp (RealCall.kt:267)
okhttp3.internal.connection.ConnectInterceptor.intercept (ConnectInterceptor.kt:32)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.kt:96)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.kt:83)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.kt:75)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
co.bosta.bosta_star_app.di.NetworkModuleKt$networkModule$1$invoke$provideOkHttpClient$$inlined$-addInterceptor$1.intercept (OkHttpClient.kt:1156)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.logging.HttpLoggingInterceptor.intercept (HttpLoggingInterceptor.kt:155)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp (RealCall.kt:205)
okhttp3.internal.connection.RealCall$AsyncCall.run (RealCall.kt:533)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1137)
java.lang.Thread.run (Thread.java:1012)
Caused by android.system.ErrnoException
isConnected failed: ETIMEDOUT (Connection timed out)
libcore.io.IoBridge.isConnected (IoBridge.java:334)
java.net.Socket.connect (Socket.java:646)
**okhttp3.internal.platform.Platform.connectSocket (Platform.kt:128)**
okhttp3.internal.connection.ConnectPlan.connectSocket (ConnectPlan.kt:246)
okhttp3.internal.connection.ConnectPlan.connectTcp (ConnectPlan.kt:128)
okhttp3.internal.connection.SequentialExchangeFinder.find (SequentialExchangeFinder.kt:41)
okhttp3.internal.connection.RealCall.initExchange$okhttp (RealCall.kt:267)
okhttp3.internal.connection.ConnectInterceptor.intercept (ConnectInterceptor.kt:32)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.kt:96)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.kt:83)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.kt:75)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
co.bosta.bosta_star_app.di.NetworkModuleKt$networkModule$1$invoke$provideOkHttpClient$$inlined$-addInterceptor$1.intercept (OkHttpClient.kt:1156)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.logging.HttpLoggingInterceptor.intercept (HttpLoggingInterceptor.kt:155)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:109)
okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp (RealCall.kt:205)
okhttp3.internal.connection.RealCall$AsyncCall.run (RealCall.kt:533)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1137)
java.lang.Thread.run (Thread.java:1012)
Also getting these crashes which also related to server connection
Dns.kt line 49 okhttp3.Dns$Companion$DnsSystem.lookup Fatal Exception:
java.net.UnknownHostException Unable to resolve host "host.com": No
address associated with hostname
Http2Stream.kt line 675
okhttp3.internal.http2.Http2Stream$StreamTimeout.newTimeoutException
Fatal Exception: java.net.SocketTimeoutException timeout
ConnectPlan.kt line 315 Fatal Exception:
javax.net.ssl.SSLHandshakeException SSL handshake aborted:
ssl=0x75dd3e3848: I/O error during system call, Software caused
connection abort
JvmOkio.kt line 94 okio.InputStreamSource.read Fatal Exception:
java.net.SocketException Software caused connection abort
I found as some answers suggested I must add this to my request but I still getting the crash after that
.connectTimeout(120, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
Note: I check interent connection before making an API request using this method
fun isConnected(): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val networkInfo=connectivityManager.activeNetworkInfo
val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
if (capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
return true
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
return true
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> {
return true
}
}
}
} else {
val activeNetworkInfo = connectivityManager.activeNetworkInfo
if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
return true
}
}
return false
}

Retrofit 2.3 Handling SocketTimeoutException

I'm currently using Retrofit 2.3 and RxAndroid for Android as my network communications. Its working fine most of the time. But sometimes, I get a SocketTimeOut exception (I'm assuming due to issues with the internet). I want to be able to handle this case but, putting a try catch around my retrofit calls in my activity doesn't catch this. Likewise, it doesn't go to the OnError method either (I don't see an option for an OnFailure method). The exception, instead, is shown in my RetrofitHelper class, at the return statement of the intercept method. Here is my Retrofit helper class:
public class RetrofitHelper {
/**
* The APICalls communicates with the json api of the API provider.
*/
public APICalls getAPICalls() {
final Retrofit retrofit = createRetrofit();
return retrofit.create(APICalls.class);
}
/**
* This custom client will append the "username=demo" query after every request.
*/
private OkHttpClient createOkHttpClient() {
final OkHttpClient.Builder httpClient =
new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
final Request original = chain.request();
final HttpUrl originalHttpUrl = original.url();
final HttpUrl url = originalHttpUrl.newBuilder()
.build();
// Request customization: add request headers
final Request.Builder requestBuilder = original.newBuilder()
.url(url);
final Request request = requestBuilder.build();
return chain.proceed(request);
}
});
return httpClient.build();
}
/**
* Creates a pre configured Retrofit instance
*/
private Retrofit createRetrofit() {
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create()) // Library for parsing json responses
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // Library for easier threading/background processing
.client(createOkHttpClient())
.build();
}
}
And here is my interface for my API calls
public interface APICalls {
#GET("Vehicle/VehiclePositions.json")
Single<ResponseVehiclePosition> getVehiclePositions();
#GET("TripUpdate/TripUpdates.json")
Single<ResponseTripUpdate> getTripUpdates();
}
And here is the log:
2020-06-05 15:43:34.877 10007-10007/com.samramakrishnan.campusbustracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.samramakrishnan.campusbustracker, PID: 10007
java.net.SocketTimeoutException: failed to connect to transitdata.cityofmadison.com/204.147.0.120 (port 80) from /10.0.2.16 (port 35902) after 10000ms
at libcore.io.IoBridge.connectErrno(IoBridge.java:191)
at libcore.io.IoBridge.connect(IoBridge.java:135)
at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:142)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:621)
at okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.java:63)
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:223)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:149)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:192)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:121)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:100)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at com.samramakrishnan.campusbustracker.restapi.RetrofitHelper$1.intercept(RetrofitHelper.java:55)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:185)
at okhttp3.RealCall.execute(RealCall.java:69)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:180)
at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:41)
at io.reactivex.Observable.subscribe(Observable.java:10179)
at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
at io.reactivex.Observable.subscribe(Observable.java:10179)
at io.reactivex.internal.operators.observable.ObservableSingleSingle.subscribeActual(ObservableSingleSingle.java:35)
at io.reactivex.Single.subscribe(Single.java:2558)
at io.reactivex.internal.operators.single.SingleSubscribeOn$SubscribeOnObserver.run(SingleSubscribeOn.java:89)
at io.reactivex.Scheduler$1.run(Scheduler.java:134)
at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:59)
at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:51)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
I think you are able to catch the exception by the BiConsumer in the subscribe method when you call do the GET call.
According to the source file:
public final Disposable subscribe(final Consumer<? super T> onSuccess, final Consumer<? super Throwable> onError)
so I think you can do something like:
compositeDisopsable.add(getAPICalls().getVehiclePositions()
.subscribeOn(...)
...
.subscribe( response -> {
//do what you want to do with the `response`
}, throwable -> {
if(throwable instanceOf SocketTimeoutException){
//handle your exception
});

addInterceptor intercept NullPointException. in Retrofit2

I got this error:
Fatal Exception: kotlin.KotlinNullPointerException
com.example.manager.helper.my_api.MyServiceGenerator$createService$$inlined$-addInterceptor$1.intercept (Interceptor.kt:81)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.kt:100)
okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp (RealCall.kt:197)
okhttp3.internal.connection.RealCall$AsyncCall.run (RealCall.kt:502)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1133)
java.lang.Thread.run (Thread.java:762)
And I have no idea why it caused.
What I implemented is:
val logging = HttpLoggingInterceptor()
if (BuildConfig.DEBUG) { // If Build is Debug Mode, Show Log
logging.level = HttpLoggingInterceptor.Level.BODY // Logs request and response lines and their respective headers and bodies (if present).
} else { // Otherwise, show nothing.
logging.level = HttpLoggingInterceptor.Level.NONE // No logs
}
val client = OkHttpClient.Builder()
client.addInterceptor {
val original = it.request()
val request = original.newBuilder()
.header("User-Agent", MyApp.httpUserAgent!!)
.build()
it.proceed(request)
}
client.addInterceptor(logging)
.connectTimeout(30, TimeUnit.SECONDS)
.callTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
You are not finished building of your client. That's why it's null. In general you forgot to call build() method.
That's how it have to be implemented.
val client = OkHttpClient.Builder()
.addInterceptor(logging)
.connectTimeout(30, TimeUnit.SECONDS)
.callTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build()
If you're using !! in your codes you should use it with a null check. Like this
if(MyApp.httpUserAgent != null) {
val request = original.newBuilder()
.header("User-Agent", MyApp.httpUserAgent!!)
.build()
else {
//here do something in case of null
}
I have the same problem when upgrade logging-interceptor from 3.10.0 to 4.7.2
Debug find cause is ssl factory
// old code
builder.sslSocketFactory(sslSocketFactory)
change the code to new code
// new code
builder.sslSocketFactory(sslSocketFactory, x509TrustManager)

Retrofit Json data truncated

I am using Retrofit and RxAndroid to send GET request to server which is based on Django, and the server response with a JSON data.
The interesting thing i found is, with stetho, the last right brace of Json is lost. So i got this error msg:
W/System.err: java.io.EOFException: End of input at line 1 column 812 path $.user
W/System.err: at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:1393)
W/System.err: at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:482)
W/System.err: at com.google.gson.stream.JsonReader.hasNext(JsonReader.java:414)
W/System.err: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:214)
W/System.err: at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
W/System.err: at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
W/System.err: at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:117)
W/System.err: at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:211)
W/System.err: at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
W/System.err: at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$RequestArbiter.request(RxJavaCallAdapterFactory.java:171)
W/System.err: at rx.Subscriber.setProducer(Subscriber.java:211)
W/System.err: at rx.internal.operators.OnSubscribeMap$MapSubscriber.setProducer(OnSubscribeMap.java:102)
W/System.err: at rx.Subscriber.setProducer(Subscriber.java:205)
W/System.err: at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call(RxJavaCallAdapterFactory.java:152)
W/System.err: at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call(RxJavaCallAdapterFactory.java:138)
W/System.err: at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
W/System.err: at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
W/System.err: at rx.Observable.unsafeSubscribe(Observable.java:10142)
W/System.err: at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:48)
W/System.err: at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:33)
W/System.err: at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
W/System.err: at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
W/System.err: at rx.Observable.unsafeSubscribe(Observable.java:10142)
W/System.err: at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:48)
W/System.err: at rx.internal.operators.OnSubscribeMap.call(OnSubscribeMap.java:33)
W/System.err: at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
W/System.err: at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
W/System.err: at rx.Observable.unsafeSubscribe(Observable.java:10142)
W/System.err: at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
W/System.err: at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
W/System.err: at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:457)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
W/System.err: at java.lang.Thread.run(Thread.java:764)
Here is the json data from stetho:
{"id":47,"credit_card":"","order_ordereditem_set":[{"id":36,"product_item":{"id":3,"category":{"id":1,"name":"Fruit"},"added_time":"2018-02-11 15:23:21","upc":"4321","desc":"Mandarin","price":150,"img_url":"http://15.32.134.74:8000/media/images/products/mandarin.jpg","not_sale":false,"is_hot":false,"is_recommended":false},"added_time":"2018-02-12 14:02:11","quantity":1,"order_id":47},{"id":37,"product_item":{"id":2,"category":{"id":1,"name":"Fruit"},"added_time":"2018-02-08 13:29:07","upc":"123456","desc":"Kiwi","price":500,"img_url":"http://15.32.134.74:8000/media/images/products/kiwi.jpg","not_sale":false,"is_hot":true,"is_recommended":false},"added_time":"2018-02-12 14:02:11","quantity":1,"order_id":47}],"added_time":"2018-02-12 14:02:11","payment":"0","total_quantity":2,"total_price":6.5,"user":1
But i checked wireshark, there is no missing of right brace.
I also used postman, but there is no problem.
This issue comes out 30%.
Following is my code details:
private HttpUtil() {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.create();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(getOkHttpClient())
.baseUrl(SERVER_BASE_URL)
.build();
mService = retrofit.create(RestAPIService.class);
}
static public HttpUtil getHttpUtilInstance() {
if (mHttpUtil == null) {
synchronized (HttpUtil.class) {
mHttpUtil = new HttpUtil();
}
}
return mHttpUtil;
}
public RestAPIService getService() {
return mService;
}
private OkHttpClient getOkHttpClient() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
if (GlobalConfig.CONFIG_DEBUG)
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
else
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
OkHttpClient.Builder httpClientBuilder = new OkHttpClient
.Builder();
httpClientBuilder.addInterceptor(loggingInterceptor)
.addInterceptor(mTokenInterceptor)
.addNetworkInterceptor(new StethoInterceptor());
//httpClientBuilder.addNetworkInterceptor(loggingInterceptor);
return httpClientBuilder.build();
}
private boolean shouldAddToken(String url) {
return !url.contains("api/login");
}
private boolean alreadyHasAuthorizationHeader(Request request) {
return request.header("Authorization") != null;
}
// Interceptor used for inserting token into Header
private Interceptor mTokenInterceptor = new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request;
Request originalRequest = chain.request();
//request = originalRequest.newBuilder().addHeader("Connection", "close").build();
request = originalRequest;
String token = UserDataRepository.getInstance().getToken();
if (token == null || token.length() == 0 || alreadyHasAuthorizationHeader(originalRequest)) {
return chain.proceed(originalRequest);
}
if (shouldAddToken(originalRequest.url().toString())) {
request = request.newBuilder()
.header("Authorization", "JWT " + token)
.build();
}
return chain.proceed(request);
}
};
#Headers({"Content-Type: application/json", "Accept: application/json"})
#GET("api/order")
Observable<List<Order>> getOrder();
it's a bit late for the answer, but if someone has the same problem, I'll tell you how I solved it.
I was having the same error, the last character of the response was missing, but when testing the api with postman everything was fine, so I try the same code with other apis and it works.
The problem is the server, I was using laravel server so I installed and configured apache and the problem is solved.

Rxjava + Retrofit Throwing OutOfMemoryError

When I use Retrofit with rxjava, some machine throwing OOM, this is log:
java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:59)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.OutOfMemoryError: pthread_create (1040KB stack) failed: Try again
at java.lang.Thread.nativeCreate(Native Method)
at java.lang.Thread.start(Thread.java:1063)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:920)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1338)
at okhttp3.ConnectionPool.put(ConnectionPool.java:135)
at okhttp3.OkHttpClient$1.put(OkHttpClient.java:149)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:188)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:129)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:98)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:109)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:124)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:145)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:170)
at okhttp3.RealCall.execute(RealCall.java:60)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$RequestArbiter.request(RxJavaCallAdapterFactory.java:171)
at rx.internal.operators.OperatorSubscribeOn$1$1$1.request(OperatorSubscribeOn.java:80)
at rx.Subscriber.setProducer(Subscriber.java:209)
at rx.internal.operators.OperatorSubscribeOn$1$1.setProducer(OperatorSubscribeOn.java:76)
at rx.Subscriber.setProducer(Subscriber.java:205)
at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call(RxJavaCallAdapterFactory.java:152)
at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call(RxJavaCallAdapterFactory.java:138)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.Observable.unsafeSubscribe(Observable.java:9861)
at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
at rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:221)
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
my retrofit code:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
if (BuildConfig.LOG_DEBUG)
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
else
interceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.retryOnConnectionFailure(true)
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(ConstantValue.URL + "/")
.client(client)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
and my request code:
public interface GetUserFriendUsersService {
#FormUrlEncoded
#POST("IM/GetUserFriendUsers")
Observable<ResponseBody> getUserFriendUsers(#Field("UserID")String UserID);}
public void getUserFriendUsers(String userID, Subscriber<List<Users>> subscriber) {
retrofit.create(GetUserFriendUsersService.class)
.getUserFriendUsers(userID)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.map(new HttpResultFunc())
.map(new Func1<JSONObject, List<Users>>() {
#Override
public List<Users> call(JSONObject jsonObject) {
List<Users> users = JSON.parseArray(jsonObject.getString("users"), Users.class);
if (users.size() == 0)
throw new CustomizeException("no data");
return users;
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
The .observeOn() should be in front of map(),and in back of unsubscribeOn()
Posted the same question at RxAndroid github.
The problem is that Schedulers.io() uses a cached thread pool without a limit and thus is trying to create 1500 threads. You should consider using a Scheduler that has a fixed limit of threads, or using RxJava 2.x's parallel() operator to parallelize the operation to a fixed number of workers.
If you're using raw Retrofit by default it uses OkHttp's dispatcher which limits the threads to something like 64 (with a max of 5 per host). That's why you aren't seeing it fail.
If you use createAsync() when creating the RxJava2CallAdapterFactory it will create fully-async Observable instances that don't require a subscribeOn and which use OkHttp's Dispatcher just like Retrofit would otherwise. Then you only need observeOn to move back to the main thread, and you avoid all additional thread creation.

Categories

Resources