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

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
}

Related

Constant Dns.java line 5 errors on crashlytics

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.

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
});

certificatePinner not working with okhttp throwing SSLHandshakeException: CertPathValidatorException Trust anchor for certification path not found

I've taken the code from Square's own github Readme:
#Throws(Exception::class)
fun run() {
val client = OkHttpClient.Builder()
.certificatePinner(CertificatePinner.Builder()
.add("api.somewebsite.nl", "sha256/SOME_KEY/SOME_KEY")
.build())
.build()
val request = Request.Builder()
.url("https://api.somewebsite.nl")
.build()
try {
val response = client.newCall(request).execute()
if (!response.isSuccessful) {
Log.i("TestCode","is Not Successful")
throw IOException("Unexpected code $response")
} else {
Log.i("TestCode","is Successful")
}
for (certificate in response.handshake()!!.peerCertificates()) {
println(CertificatePinner.pin(certificate))
}
} catch (e: SSLHandshakeException) {
e.printStackTrace()
}
}
When going to this website using Chrome it works, indicating that the App has the Comodo CA certificate on the particular phone. For the SHA256 pin value I went to this site. This site is also mentioned in this excellent walkthrough.
I've used the latest versions of the libraries:
implementation "com.squareup.retrofit2:retrofit:2.5.0"
implementation "com.squareup.retrofit2:converter-moshi:2.5.0"
implementation "com.squareup.okhttp3:okhttp:3.14.1"
Here is the Logging:
E/Conscrypt: ------------------Untrusted chain: ----------------------
E/Conscrypt: == Chain0 ==
Version: 3
E/Conscrypt: Serial Number: serial_number
E/Conscrypt: SubjectDN: CN=*.somewebsite.nl, OU=PremiumSSL Wildcard, OU=IT, O=somewebsite B.V., STREET=some_street, L=SomeCity, ST=SomeCity, OID.2.5.4.17=POSTAL_CODE, C=NL
E/Conscrypt: IssuerDN: CN=Sectigo RSA Organization Validation Secure Server CA, O=Sectigo Limited, L=Salford, ST=Greater Manchester, C=GB
E/Conscrypt: Get not before: Mon May 06 02:00:00 GMT+02:00 2019
E/Conscrypt: Get not after: Mon Jul 05 01:59:59 GMT+02:00 2021
E/Conscrypt: Sig ALG name: SHA256withRSA
E/Conscrypt: Signature: SOME_SIGNATURE
E/Conscrypt: Public key:
W/System.err: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:361)
W/System.err: at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:336)
W/System.err: at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:300)
W/System.err: at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:185)
W/System.err: at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.java:224)
W/System.err: at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.java:107)
W/System.err: at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.java:87)
W/System.err: at okhttp3.internal.connection.Transmitter.newExchange(Transmitter.java:169)
W/System.err: at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:41)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
W/System.err: at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:94)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
W/System.err: at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
W/System.err: at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:88)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:142)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:117)
W/System.err: at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:221)
W/System.err: at okhttp3.RealCall.execute(RealCall.java:81)
Try to Modify OkHttpClient.Builder Object: see this solution

Glide and Picasso Failed to load resource, javax.net.ssl.SSLHandshakeException for API 19

i am facing this glide and picasso javax.net.ssl.SSLHandshakeException for below API 19 (KITKAT), its working fine on Above 23 (Lollipop).
here is the logcat for Glide
11-13 15:17:56.205 11198-11198/com.oceanleaguewebcranks.app W/Glide: Load failed for http://server9host.com/ocean/oceans/category/Jellyfish.jpg with size [374x200]
class com.bumptech.glide.load.engine.GlideException: Failed to load resource
There was 1 cause:
javax.net.ssl.SSLHandshakeException(javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x73fa4490: Failure in SSL library, usually a protocol error
error:14077102:SSL routines:SSL23_GET_SERVER_HELLO:unsupported protocol (external/openssl/ssl/s23_clnt.c:714 0x73fc8cfc:0x00000000))
call GlideException#logRootCauses(String) for more detail
Cause (1 of 1): class com.bumptech.glide.load.engine.GlideException: Fetching data failed, class java.io.InputStream, REMOTE
There was 1 cause:
javax.net.ssl.SSLHandshakeException(javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x73fa4490: Failure in SSL library, usually a protocol error
error:14077102:SSL routines:SSL23_GET_SERVER_HELLO:unsupported protocol (external/openssl/ssl/s23_clnt.c:714 0x73fc8cfc:0x00000000))
call GlideException#logRootCauses(String) for more detail
Cause (1 of 1): class com.bumptech.glide.load.engine.GlideException: Fetch failed
There was 1 cause:
javax.net.ssl.SSLHandshakeException(javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x73fa4490: Failure in SSL library, usually a protocol error
error:14077102:SSL routines:SSL23_GET_SERVER_HELLO:unsupported protocol (external/openssl/ssl/s23_clnt.c:714 0x73fc8cfc:0x00000000))
call GlideException#logRootCauses(String) for more detail
Cause (1 of 1): class javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x73fa4490: Failure in SSL library, usually a protocol error
error:14077102:SSL routines:SSL23_GET_SERVER_HELLO:unsupported protocol (external/openssl/ssl/s23_clnt.c:714 0x73fc8cfc:0x00000000)
11-13 15:17:56.205 11198-11198/com.oceanleaguewebcranks.app I/Glide: Root cause (1 of 1)
javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x73fa4490: Failure in SSL library, usually a protocol error
error:14077102:SSL routines:SSL23_GET_SERVER_HELLO:unsupported protocol (external/openssl/ssl/s23_clnt.c:714 0x73fc8cfc:0x00000000)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:449)
at com.android.okhttp.Connection.upgradeToTls(Connection.java:146)
at com.android.okhttp.Connection.connect(Connection.java:107)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
at com.android.okhttp.internal.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:161)
at com.bumptech.glide.load.data.HttpUrlFetcher.loadDataWithRedirects(HttpUrlFetcher.java:104)
at com.bumptech.glide.load.data.HttpUrlFetcher.loadDataWithRedirects(HttpUrlFetcher.java:122)
at com.bumptech.glide.load.data.HttpUrlFetcher.loadData(HttpUrlFetcher.java:59)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:99)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.startNextOrFail(MultiModelLoader.java:150)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.onLoadFailed(MultiModelLoader.java:144)
at com.bumptech.glide.load.data.HttpUrlFetcher.loadData(HttpUrlFetcher.java:65)
at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:99)
at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:62)
at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:302)
at com.bumptech.glide.load.engine.DecodeJob.runWrapped(DecodeJob.java:272)
at com.bumptech.glide.load.engine.DecodeJob.run(DecodeJob.java:233)
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:841)
at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$1.run(GlideExecutor.java:446)
Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x73fa4490: Failure in SSL library, usually a protocol error
error:14077102:SSL routines:SSL23_GET_SERVER_HELLO:unsupported protocol (external/openssl/ssl/s23_clnt.c:714 0x73fc8cfc:0x00000000)
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:406)
... 24 more
and picasso is not returning any log.
this is a library error or its a server SSL Exception, if is Server error then how to solve...?
TLS 1.2 is not enabled by default in API <= 19.
You need to manually enable it.
For Glide and Volley HTTP client:
In your Glide App Module, (that extends AppGlideModule)
#Override
public void registerComponents(#NonNull Context context, #NonNull Glide glide, #NonNull Registry registry) {
RequestQueue requestQueue;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
HttpStack stack = null;
try {
stack = new HurlStack(null, new TLSSocketFactory());
} catch (KeyManagementException e) {
stack = new HurlStack();
} catch (NoSuchAlgorithmException e) {
stack = new HurlStack();
}
requestQueue = Volley.newRequestQueue(context, stack);
} else {
requestQueue = Volley.newRequestQueue(context);
}
RequestQueue requestQueue = VolleySingleton.getInstance(context);
requestQueue.start();
glide.getRegistry().replace(GlideUrl.class, InputStream.class, new VolleyUrlLoader.Factory(requestQueue));
}
TLSSocketFactory can be found in https://gist.github.com/fkrauthan/ac8624466a4dee4fd02f#file-tlssocketfactory-java
For Glide, below implementation is working for me.
Instead of LibraryGlideModule i have used AppGlideModule
GlideModule.kt
#GlideModule
class MyGlideModule : AppGlideModule() {
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
registry.replace(
GlideUrl::class.java,
InputStream::class.java,
OkHttpUrlLoader.Factory(UnsafeOkHttpClient.unsafeOkHttpClient)
)
}
}
UnsafeOkHttpClient.kt
object UnsafeOkHttpClient {
// Create a trust manager that does not validate certificate chains
val unsafeOkHttpClient:
OkHttpClient
get() = try {
// Create a trust manager that does not validate certificate chains
val trustAllCerts: Array<TrustManager> = arrayOf<TrustManager>(
object : X509TrustManager {
#Throws(CertificateException::class)
override fun checkClientTrusted(
chain: Array<X509Certificate?>?,
authType: String?
) {
}
#Throws(CertificateException::class)
override fun checkServerTrusted(
chain: Array<X509Certificate?>?,
authType: String?
) {
}
override fun getAcceptedIssuers(): Array<X509Certificate?>? {
return arrayOf()
}
}
)
val sslContext: SSLContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory: SSLSocketFactory = sslContext.socketFactory
val builder: OkHttpClient.Builder = OkHttpClient.Builder()
builder.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
builder.hostnameVerifier(HostnameVerifier { hostname, session -> true })
builder.build()
} catch (e: Exception) {
throw RuntimeException(e)
}
}
AndroidManifiest
<meta-data
android:name="yourpackagename.MyGlideModule"
android:value="AppGlideModule" />

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.

Categories

Resources