How to pass a Bearer API Key in Retrofit2? - android

Two possibilities : either i pass a header with "Authorization: APIKEY" but it says that i don't have access (code 401) or i pass "Authorization: Bearer APIKEY" and it throws an exception. After looking up on SO i found the solution to add interceptor, also to add a header with "Connection: close" but still, i don't receive the data.
Here's my code :
public class RetrofitYouSign {
private static Retrofit sRetrofit;
private static final String URL = "https://staging-api.yousign.com/";
private static OkHttpClient sOkHttpClient = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("Authorization", "Bearer MY-API-KEY")
.addHeader("Content-Type", "application/json")
.addHeader("Connection", "close")
.build();
return chain.proceed(request);
}
}).build();
public static Retrofit getRetrofit(){
if (sRetrofit == null) {
sRetrofit = new Retrofit.Builder()
.client(sOkHttpClient)
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return sRetrofit;
}
public interface GetYouSign {
#GET("users/")
Call<Yousign> getYouSignData();
}
}```
And here is my stack if i enter with the name Bearer :
2019-04-11 19:25:12.894 1492-1492/com.jmjsolution.solarup I/System.out: [okhttp3.internal.http.StatusLine.parse(StatusLine.java:69), okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189), okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88), okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147), okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45), okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147), okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121), okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93), okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147), okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121), okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93), okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147), okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126), okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147), okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121), com.jmjsolution.solarpro.services.retrofitClient.RetrofitYouSign$1.intercept(RetrofitYouSign.java:31), okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147), okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121), okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200), okhttp3.RealCall$AsyncCall.execute(RealCall.java:147), okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32), java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162), java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636), java.lang.Thread.run(Thread.java:764)]
2019-04-11 19:25:12.894 1492-1492/com.jmjsolution.solarup W/System.err: java.net.ProtocolException: Unexpected status line: ��
2019-04-11 19:25:12.894 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.StatusLine.parse(StatusLine.java:69)
2019-04-11 19:25:12.894 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189)
2019-04-11 19:25:12.894 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88)
2019-04-11 19:25:12.895 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
2019-04-11 19:25:12.895 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
2019-04-11 19:25:12.895 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
2019-04-11 19:25:12.895 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
2019-04-11 19:25:12.895 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
2019-04-11 19:25:12.895 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
2019-04-11 19:25:12.895 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
2019-04-11 19:25:12.895 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
2019-04-11 19:25:12.896 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
2019-04-11 19:25:12.896 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
2019-04-11 19:25:12.897 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
2019-04-11 19:25:12.897 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
2019-04-11 19:25:12.897 1492-1492/com.jmjsolution.solarup W/System.err: at com.jmjsolution.solarpro.services.retrofitClient.RetrofitYouSign$1.intercept(RetrofitYouSign.java:31)
2019-04-11 19:25:12.898 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
2019-04-11 19:25:12.898 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
2019-04-11 19:25:12.898 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
2019-04-11 19:25:12.898 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.RealCall$AsyncCall.execute(RealCall.java:147)
2019-04-11 19:25:12.898 1492-1492/com.jmjsolution.solarup W/System.err: at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
2019-04-11 19:25:12.898 1492-1492/com.jmjsolution.solarup W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
2019-04-11 19:25:12.898 1492-1492/com.jmjsolution.solarup W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
2019-04-11 19:25:12.898 1492-1492/com.jmjsolution.solarup W/System.err: at java.lang.Thread.run(Thread.java:764)
Otherwise i receiver a code 401, if i don't put the word Bearer.
I tried the code with the interceptor (as you can see in my code) but nothing seems to work. Any solution would be really appreciated, thank you.

try this int APiInterface class:-
#GET("users")
Call<Yousign> getYouSignData(#Header("Authorization") String token);
or in your activity like this :-
getYouSignData("Bearer your api key")

You can simply pass you (bearer + auth token) as Authorization parameter like below:
#GET("api/GetProfile)
Call<UserProfile> getProfile(#Header("Authorization") String authHeader);
then call like this
Call<UserProfile> calltargetResponce = client.getProfile("Bearer "+token);

Related

Handling http errors in retrofit and okhttp in android application

In my android application I have used retrofit and okhttp as shown in below code snippets. The application works well and I am not getting any error during testing and also on production but some times socket timeout exception, sslhandshake exceptions, unknown host exceptions are being logged in by firebase crashalytics as fatal exceptions, which means that application is being crashed when these exceptions are thrown. I have checked with our network team and they have double checked every thing at their end, but issue is still there. Is there a way that I can catch all these exceptions to avoid any fatal crashes. Here is my implementaion
class CoreDataModule {
#Provides
fun provideOkHttpClient(): OkHttpClient {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient().newBuilder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(90, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
if (BuildConfig.DEBUG) {
client.addInterceptor(interceptor)
}
client.addInterceptor { chain ->
val request = chain.request()
val response = chain.proceed(request)
response
}
return client.build()
}
#Provides
#Singleton
fun provideMoshi(): Moshi = Moshi.Builder().build()
#Provides
#Singleton
fun provideMoshiConverterFactory(): MoshiConverterFactory =
MoshiConverterFactory.create()
}
This is inside Appmodule class
#Singleton
#Provides
fun providemyappService(#appAPI okHttpClient: OkHttpClient, converterFactory: MoshiConverterFactory) =
provideService(okHttpClient, converterFactory, myappApi::class.java)
#appAPI
#Provides
fun providePrivateOkHttpClient(upstreamClient: OkHttpClient): OkHttpClient {
return upstreamClient.newBuilder().build()
}
#Singleton
#Provides
fun provideRemoteDataSource(myappService: myappApi) = RemoteDataSource(myappService)
private fun createRetrofit(
okhttpClient: OkHttpClient,
converterFactory: MoshiConverterFactory
): Retrofit {
return if (BuildConfig.DEBUG) {
Retrofit.Builder()
.baseUrl(BASE_URL_STAGE)
.client(okhttpClient)
.addConverterFactory(converterFactory)
.build()
} else {
Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okhttpClient)
.addConverterFactory(converterFactory)
.build()
}
}
private fun <T> provideService(
okhttpClient: OkHttpClient,
converterFactory: MoshiConverterFactory, clazz: Class<T>
): T {
return createRetrofit(okhttpClient, converterFactory).create(clazz)
}
This is inside API end point interface
#POST("Validate/UserValidation")
#FormUrlEncoded
suspend fun validateUser(#Field("data") data: String): Response<ValidationResponse>
Here are some crash logs from firebase console
Fatal Exception: java.net.SocketTimeoutException: failed to connect to app.com.pk/123.123.123.124 (port 443) after 15000ms
at libcore.io.IoBridge.connectErrno(IoBridge.java:191) (Note: Actual fqdn and ip replaced here)
at libcore.io.IoBridge.connect(IoBridge.java:127)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:201)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:520)
at java.net.Socket.connect(Socket.java:927)
at okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.java:73)
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:246)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:166)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:200)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
This is another stacktrace
Fatal Exception: java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:629)
at libcore.io.IoBridge.recvfrom(IoBridge.java:591)
at java.net.PlainSocketImpl.read(PlainSocketImpl.java:487)
at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:37)
at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:237)
at okio.Okio$2.read(Okio.java:140)
at okio.AsyncTimeout$2.read(AsyncTimeout.java:237)
at okio.RealBufferedSource.indexOf(RealBufferedSource.java:358)
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:230)
at okhttp3.internal.http1.Http1Codec.readHeaderLine(Http1Codec.java:215)
at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189)
at okhttp3.internal.connection.RealConnection.createTunnel(RealConnection.java:376)
at okhttp3.internal.connection.RealConnection.connectTunnel(RealConnection.java:219)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:160)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:200)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
SSL Handshake exception
Fatal Exception: javax.net.ssl.SSLHandshakeException: SSL handshake aborted: ssl=0x7fa29fd100: I/O error during system call, Connection reset by peer
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(NativeCrypto.java)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:323)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:319)
at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:283)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:168)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:200)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
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)
Unknown host exception
Fatal Exception: java.net.UnknownHostException: Unable to resolve host "app.com.pk": No address associated with hostname Note:ACtual FQDN changed here
at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at okhttp3.Dns$1.lookup(Dns.java:40)
at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:185)
at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:149)
at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:84)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:214)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:200)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
I am using retrofit_version = "2.6.0"

Android app crashes with StackOverflowError Retrofit 2 + RxJava 1

I'm using Retrofit2 with RxJava1 to make network calls and I'm getting the following crash logs from my users through Crashlytics quite often.
I can't really pinpoint the issue and neither have I been able to reproduce this crash on my end.
Can anyone suggest why it could be happening?
One of my guesses is it might have something to do with me using RxJava1 + Retrofit2 but haven't found any concrete evidence for that yet.
Upgrading the whole app to RxJava2 will be a huge effort which I want to keep as a last resort to try.
I'm using the following RxJava and Retrofit dependencies :
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.1.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
implementation 'moe.banana:moshi-jsonapi:3.3.1'
implementation 'io.reactivex:rxandroid:1.2.1'
implementation 'io.reactivex:rxjava:1.1.6'
Some device observations:
Operating Systems : Android 9 and 10 (not sure if happening on previous versions as well)
Background state : 53% in background
Rooted : No
The code near line 45 of my Interceptor class pointed in logs is :
#Override
public Response intercept(Chain chain) throws IOException {
Request.Builder requestBuilder = chain.request().newBuilder();
requestBuilder = addDefaultHeaders(requestBuilder);
requestBuilder = addAuthorizationHeader(requestBuilder);
requestBuilder = addSocketHeader(requestBuilder);
requestBuilder = addCustomHeaders(requestBuilder);
return chain.proceed(requestBuilder.build()); // Line 45
}
Also, the code near line 48 of my TokenAuthenticator class pointed in logs is :
#Override
public Request authenticate(Route route, Response response) throws IOException {
if (response.code() == HttpsURLConnection.HTTP_UNAUTHORIZED) {
Log.d(TAG, "Code 401 received when making API call");
retrofit2.Response<JwtToken> refreshResponse =
mAuthenticationRepository.authRefresh().execute(); // Line 48
I'm making REST calls in general in the following way :
Observable<ItemRealm> localItem = mItemLocalDataSource.getItem(itemId);
Observable<ItemRealm> remoteItem = apiService()
.getItem(itemId)
.flatMap((Func1<Item, Observable<ItemRealm>>) item -> {
Realm realm = Realm.getDefaultInstance();
try {
mItemLocalDataSource.saveItem(item, realm);
return mItemLocalDataSource.getItem(itemId, realm);
} finally {
realm.close();
}
});
return Observable.merge(localItem, remoteItem);
The following are the crash logs :
Fatal Exception: java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:62)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:459)
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:764)
Caused by java.lang.StackOverflowError: stack size 1041KB
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:175)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.soapboxhq.goodtalk_android.data.remote.TeamApiInterceptor.intercept(TeamApiInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:89)
at com.soapboxhq.goodtalk_android.data.remote.TokenAuthenticator.authenticate(TokenAuthenticator.java:48)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.followUpRequest(RetryAndFollowUpInterceptor.java:288)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:158)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.soapboxhq.goodtalk_android.data.remote.TeamApiInterceptor.intercept(TeamApiInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:89)
at com.soapboxhq.goodtalk_android.data.remote.TokenAuthenticator.authenticate(TokenAuthenticator.java:48)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.followUpRequest(RetryAndFollowUpInterceptor.java:288)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:158)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.soapboxhq.goodtalk_android.data.remote.TeamApiInterceptor.intercept(TeamApiInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:89)
at com.soapboxhq.goodtalk_android.data.remote.TokenAuthenticator.authenticate(TokenAuthenticator.java:48)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.followUpRequest(RetryAndFollowUpInterceptor.java:288)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:158)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.soapboxhq.goodtalk_android.data.remote.TeamApiInterceptor.intercept(TeamApiInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:89)
at com.soapboxhq.goodtalk_android.data.remote.TokenAuthenticator.authenticate(TokenAuthenticator.java:48)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.followUpRequest(RetryAndFollowUpInterceptor.java:288)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:158)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.soapboxhq.goodtalk_android.data.remote.TeamApiInterceptor.intercept(TeamApiInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:89)
at com.soapboxhq.goodtalk_android.data.remote.TokenAuthenticator.authenticate(TokenAuthenticator.java:48)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.followUpRequest(RetryAndFollowUpInterceptor.java:288)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:158)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.soapboxhq.goodtalk_android.data.remote.TeamApiInterceptor.intercept(TeamApiInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:89)
at com.soapboxhq.goodtalk_android.data.remote.TokenAuthenticator.authenticate(TokenAuthenticator.java:48)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.followUpRequest(RetryAndFollowUpInterceptor.java:288)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:158)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.soapboxhq.goodtalk_android.data.remote.TeamApiInterceptor.intercept(TeamApiInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:89)
at com.soapboxhq.goodtalk_android.data.remote.TokenAuthenticator.authenticate(TokenAuthenticator.java:48)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.followUpRequest(RetryAndFollowUpInterceptor.java:288)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:158)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.soapboxhq.goodtalk_android.data.remote.TeamApiInterceptor.intercept(TeamApiInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:89)
at com.soapboxhq.goodtalk_android.data.remote.TokenAuthenticator.authenticate(TokenAuthenticator.java:48)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.followUpRequest(RetryAndFollowUpInterceptor.java:288)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:158)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.soapboxhq.goodtalk_android.data.remote.TeamApiInterceptor.intercept(TeamApiInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:89)
at com.soapboxhq.goodtalk_android.data.remote.TokenAuthenticator.authenticate(TokenAuthenticator.java:48)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.followUpRequest(RetryAndFollowUpInterceptor.java:288)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:158)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.soapboxhq.goodtalk_android.data.remote.TeamApiInterceptor.intercept(TeamApiInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:89)
at com.soapboxhq.goodtalk_android.data.remote.TokenAuthenticator.authenticate(TokenAuthenticator.java:48)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.followUpRequest(RetryAndFollowUpInterceptor.java:288)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:158)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.soapboxhq.goodtalk_android.data.remote.TeamApiInterceptor.intercept(TeamApiInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$RequestArbiter.request(RxJavaCallAdapterFactory.java:171)
at rx.Subscriber.setProducer(Subscriber.java:211)
at rx.internal.operators.OperatorMap$MapSubscriber.setProducer(OperatorMap.java:99)
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:50)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:50)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:50)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.Observable.unsafeSubscribe(Observable.java:8666)
at rx.internal.operators.OperatorMerge$MergeSubscriber.onNext(OperatorMerge.java:250)
at rx.internal.operators.OperatorMerge$MergeSubscriber.onNext(OperatorMerge.java:147)
at rx.internal.operators.OnSubscribeFromArray$FromArrayProducer.fastPath(OnSubscribeFromArray.java:76)
at rx.internal.operators.OnSubscribeFromArray$FromArrayProducer.request(OnSubscribeFromArray.java:58)
at rx.Subscriber.setProducer(Subscriber.java:211)
at rx.internal.operators.OnSubscribeFromArray.call(OnSubscribeFromArray.java:32)
at rx.internal.operators.OnSubscribeFromArray.call(OnSubscribeFromArray.java:24)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:50)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.Observable.unsafeSubscribe(Observable.java:8666)
at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
at rx.internal.schedulers.CachedThreadScheduler$EventLoopWorker$1.call(CachedThreadScheduler.java:220)
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:459)
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:764)
Any help would be greatly appreciated.
And please let me know if you need any further information.

SSLHandshakeException while retrieving data from TheMovieDataBase using Retrofit+OkHttp in Android

I am trying to fetch list of movies from TheMovieDatabase(TMDb)
Get: https://api.themoviedb.org/3/movie/now_playing?api_key=${KEY}&page=1
However, I am getting the following:
HTTP FAILED: javax.net.ssl.SSLHandshakeException: Connection closed by
peer
Following is the code I have already tried:
if (okHttpClient == null) {
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS) //tried MODERN_TLS also
.tlsVersions(TlsVersion.TLS_1_2)
.supportsTlsExtensions(true)
.cipherSuites(
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
)
.build();
okHttpClient = new OkHttpClient.Builder()
.connectionSpecs(Collections.singletonList(spec))
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.addInterceptor(logging)
.build();
}
if (retrofit == null)
retrofit = new Retrofit.Builder()
.baseUrl(APIUtils.BASE_URL)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
Logs:
javax.net.ssl.SSLHandshakeException: Connection closed by peer
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:324)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:318)
at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:282)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:167)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:213)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at com.google.firebase.perf.network.FirebasePerfOkHttpClient.execute(Unknown
Source)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:180)
at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:42)
at io.reactivex.Observable.subscribe(Observable.java:12030)
at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
at io.reactivex.Observable.subscribe(Observable.java:12030)
at io.reactivex.internal.operators.observable.ObservableObserveOn.subscribeActual(ObservableObserveOn.java:45)
at io.reactivex.Observable.subscribe(Observable.java:12030)
at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:579)
at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:269)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)

App crashes on java.net.SocketTimeoutException: timeout (Kotlin, Retrofit)

App crashes on this line if response won't come.
chain.proceed(requestBuilder.build())
Here is my class for RetrofitClient
class RetrofitClient {
private val apiService: ApiServiceInterface
init {
val builder = Retrofit.Builder()
builder.baseUrl(RequestParameters.BASE_URL)
builder.addConverterFactory(GsonConverterFactory.create())
builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//added for adapter
builder.client(getClient())
val retrofit = builder.build()
apiService = retrofit.create(ApiServiceInterface::class.java)
}
companion object {
private var clientInstance: RetrofitClient? = null
lateinit var context: Context
fun getInstance(): RetrofitClient {
if (clientInstance == null) {
clientInstance = RetrofitClient()
}
return clientInstance as RetrofitClient
}
}
fun getApiInterface(): ApiServiceInterface {
return apiService
}
private fun getClient(): OkHttpClient {
val httpClient = OkHttpClient.Builder()
httpClient.readTimeout(25, TimeUnit.SECONDS)
httpClient.connectTimeout(25, TimeUnit.SECONDS)
httpClient.addInterceptor { chain ->
val original = chain.request()
val requestBuilder = original.newBuilder()
.header(RequestParameters.X_API, RequestParameters.H_XAPI_KEY)
.method(original.method(), original.body())
chain.proceed(requestBuilder.build())
}
// set your desired log level
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.HEADERS
logging.level = HttpLoggingInterceptor.Level.BODY
httpClient.addInterceptor(logging)
return httpClient.build()
}
}
Here is the error in log:
1542609097.397 26572-26572/com.app.mylife W/System.err: java.net.SocketTimeoutException: timeout
1542609097.397 26572-26572/com.app.mylife W/System.err: at okio.Okio$4.newTimeoutException(Okio.java:230)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okio.AsyncTimeout.exit(AsyncTimeout.java:285)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okio.AsyncTimeout$2.read(AsyncTimeout.java:241)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okio.RealBufferedSource.indexOf(RealBufferedSource.java:345)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:217)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http1.Http1Codec.readHeaderLine(Http1Codec.java:212)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:125)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:212)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
1542609097.398 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
1542609097.398 26572-26572/com.app.mylife W/System.err: at com.app.mylife.retrofit.RetrofitClient$getClient$1.intercept(RetrofitClient.kt:64)
1542609097.399 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
1542609097.399 26572-26572/com.app.mylife W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
1542609097.399 26572-26572/com.app.mylife W/System.err: at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
1542609097.399 26572-26572/com.app.mylife W/System.err: at okhttp3.RealCall.execute(RealCall.java:77)
1542609097.399 26572-26572/com.app.mylife W/System.err: at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
1542609097.399 26572-26572/com.app.mylife W/System.err: at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:41)
1542609097.399 26572-26572/com.app.mylife W/System.err: at io.reactivex.Observable.subscribe(Observable.java:10179)
1542609097.399 26572-26572/com.app.mylife W/System.err: at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
1542609097.399 26572-26572/com.app.mylife W/System.err: at io.reactivex.Observable.subscribe(Observable.java:10179)
1542609097.399 26572-26572/com.app.mylife W/System.err: at io.reactivex.internal.operators.observable.ObservableSubscribeOn$1.run(ObservableSubscribeOn.java:39)
1542609097.399 26572-26572/com.app.mylife W/System.err: at io.reactivex.Scheduler$1.run(Scheduler.java:134)
1542609097.399 26572-26572/com.app.mylife W/System.err: at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:59)
1542609097.399 26572-26572/com.app.mylife W/System.err: at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:51)
1542609097.399 26572-26572/com.app.mylife W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
1542609097.399 26572-26572/com.app.mylife W/System.err: at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
1542609097.399 26572-26572/com.app.mylife W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
1542609097.399 26572-26572/com.app.mylife W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
1542609097.399 26572-26572/com.app.mylife W/System.err: at java.lang.Thread.run(Thread.java:764)
1542609097.399 26572-26572/com.app.mylife W/System.err: Caused by: java.net.SocketException: Socket closed
1542609097.399 26572-26572/com.app.mylife W/System.err: at java.net.SocketInputStream.read(SocketInputStream.java:203)
1542609097.399 26572-26572/com.app.mylife W/System.err: at java.net.SocketInputStream.read(SocketInputStream.java:139)
1542609097.399 26572-26572/com.app.mylife W/System.err: at okio.Okio$2.read(Okio.java:139)
1542609097.399 26572-26572/com.app.mylife W/System.err: at okio.AsyncTimeout$2.read(AsyncTimeout.java:237)
1542609097.400 26572-26572/com.app.mylife W/System.err: ... 39 more
Try this code way..
make retrofit object creation part.
class ApiClient {
companion object {
val BASE_URL = "https://simplifiedcoding.net/demos/"
var retrofit: Retrofit? = null
fun getClient(): Retrofit? {
if (retrofit == null) {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder().apply {
readTimeout(20, TimeUnit.SECONDS)
writeTimeout(20, TimeUnit.SECONDS)
connectTimeout(20, TimeUnit.SECONDS)
addInterceptor(interceptor)
addInterceptor { chain ->
var request = chain.request()
request = request.newBuilder()
.build()
val response = chain.proceed(request)
response
}
}
retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit
}
}
}
make interface for api calling..
interface ApiInterface {
#GET("marvel")
fun getData(): Call<List<Hero>>
}
In activity or fragment called api like this way i hope you create response pojo class
var apiInterface: ApiInterface = ApiClient.getClient()!!.create(ApiInterface::class.java)
var hero: Call<List<Hero>>
hero = apiInterface.getData()
hero.enqueue(object : Callback<List<Hero>> {
override fun onFailure(call: Call<List<Hero>>?, t: Throwable?) {
closeDialog(dialog)
Toast.makeText(mContext, t?.message, Toast.LENGTH_SHORT).show()
Log.d("Error:::",t?.message)
}
override fun onResponse(call: Call<List<Hero>>?, response: Response<List<Hero>>?) {
mHeroDataList.clear()
if (response != null && response.isSuccessful && response.body() != null) {
closeDialog(dialog)
mHeroDataList .addAll(response.body()!!)
setAdapter(mHeroDataList)
}
}
})
This code throws Exception when there is no network. So you can catch the exception using try and catch block. You can put try and catch where your are calling the network. And it won't crash your App again.

Retrofit FATAL EXCEPTION: OkHttp Dispatcher, java.lang.NullPointerException: interceptor

App crash always on this point if there is no internet or return null.
Following is log
FATAL EXCEPTION: OkHttp Dispatcher
Process: , PID: 24400
java.lang.NullPointerException: interceptor
RestClient$1#301dd345 returned null
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:157)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:147)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
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)
Here is Log
05-01 09:17:37.920 24400-24439/? D/OkHttp: --> END GET
05-01 09:17:37.922 24400-24439/? D/OkHttp: <-- HTTP FAILED: java.net.UnknownHostException: Unable to resolve host "": No address associated with hostname
05-01 09:17:37.923 24400-24439/? W/System.err: java.net.UnknownHostException: Unable to resolve host "": No address associated with hostname
05-01 09:17:37.923 24400-24439/? W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:427)
05-01 09:17:37.924 24400-24439/? W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
05-01 09:17:37.924 24400-24439/? W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:215)
05-01 09:17:37.924 24400-24439/? W/System.err: at okhttp3.Dns$1.lookup(Dns.java:39)
05-01 09:17:37.924 24400-24439/? W/System.err: at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:185)
05-01 09:17:37.924 24400-24439/? W/System.err: at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:149)
05-01 09:17:37.925 24400-24439/? W/System.err: at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:84)
05-01 09:17:37.925 24400-24439/? W/System.err: at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:213)
05-01 09:17:37.927 24400-24439/? W/System.err: at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:134)
05-01 09:17:37.927 24400-24439/? W/System.err: at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:113)
05-01 09:17:37.927 24400-24439/? W/System.err: at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
05-01 09:17:37.927 24400-24439/? W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
05-01 09:17:37.927 24400-24439/? W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
05-01 09:17:37.928 24400-24439/? W/System.err: at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
05-01 09:17:37.928 24400-24439/? W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
05-01 09:17:37.928 24400-24439/? W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
05-01 09:17:37.928 24400-24439/? W/System.err: at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
05-01 09:17:37.928 24400-24439/? W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
05-01 09:17:37.928 24400-24439/? W/System.err: at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:125)
05-01 09:17:37.929 24400-24439/? W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
05-01 09:17:37.929 24400-24439/? W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
05-01 09:17:37.929 24400-24439/? W/System.err: at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:212)
05-01 09:17:37.929 24400-24439/? W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
05-01 09:17:37.929 24400-24439/? W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
05-01 09:17:37.929 24400-24439/? W/System.err: at RestClient$1.intercept(RestClient.java:66)
05-01 09:17:37.929 24400-24439/? W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
05-01 09:17:37.929 24400-24439/? W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
05-01 09:17:37.929 24400-24439/? W/System.err: at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
05-01 09:17:37.929 24400-24439/? W/System.err: at okhttp3.RealCall$AsyncCall.execute(RealCall.java:147)
05-01 09:17:37.930 24400-24439/? W/System.err: at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
05-01 09:17:37.930 24400-24439/? W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-01 09:17:37.930 24400-24439/? W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-01 09:17:37.930 24400-24439/? W/System.err: at java.lang.Thread.run(Thread.java:818)
Its my Network class Code. Here i am making request. java.lang.NullPointerException: interceptor RestClient$1#301dd345 returned null
Another log show in same sequence show this message
D/OkHttp: <-- HTTP FAILED: java.net.UnknownHostException: Unable to resolve host "example.com": No address associated with hostname
public static String API_BASE_URL = "";
public static final String BASE_URL_QA = "https://example.com";
public static final String BASE_URL_LIVE = "https://example.com";
private Retrofit builder;
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private Response response;
public RestClient() {
if (SharedPreferenceManager.getSharedInstance().getStringFromPreferances(Constants.SharedPreferenceKeys.QA.getKey()).equals("yes")) {
BASE_URL = BASE_URL_QA;
} else {
BASE_URL = BASE_URL_LIVE;
}
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
if (!AppData.isTrue) {
httpClient.interceptors().add(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
try {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder();
if (AppData.isBearer) {
String token = getAccessToken();
String bearer = getToken_type();
if (AppUtils.getAppUtils(null).isNullOrEmpty(token) && SharedPreferenceManager.getSharedInstance().getFromPreferences() != null) {
token = SharedPreferenceManager.getToken();
bearer = SharedPreferenceManager.getTokentype();
}
requestBuilder.addHeader("Authorization", bearer + " " + token);
}
requestBuilder.addHeader("key", "");
Request request = requestBuilder.build();
AppData.isTrue = false;
response = chain.proceed(request);
} catch (Exception e) {
e.printStackTrace();
} catch (Error e2) {
Log.e("", "ROME parse error2: " + e2.toString());
}
return response;
}
});
}
httpClient.addInterceptor(logging);
OkHttpClient shortHttpClient = httpClient.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.connectTimeout(20, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build();
builder = new Retrofit.Builder().
baseUrl(BASE_URL).
addConverterFactory(new ToStringConverterFactory()).
addConverterFactory(GsonConverterFactory.create()).
addCallAdapterFactory(RxJavaCallAdapterFactory.create()).
client(shortHttpClient).
build();
}
public <S> S createService(Class<S> serviceClass) {
return builder.create(serviceClass);
}

Categories

Resources