I Implemented sample retrofit 2 response via GET type, where I click button to get the response, but I have Failure response
public interface GithubServise {
#GET("/users/waadalkatheri/repos")
Call<ResponseBody> getGithub();
}
public void loadData (View view){
String LINK = "https://api.github.com";
Retrofit retrofit = new Retrofit.Builder ().baseUrl (LINK).build ();
GithubServise githubServise= retrofit.create (GithubServise.class);
githubServise.getGithub ().enqueue (new Callback<ResponseBody> () {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
textView.setText (response.body ().string ());
Log.v ("TAG","yes");
} catch (IOException e) {
e.printStackTrace ();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
textView.setText ("no data");
}
});
}
Stacktrace
06-25 10:13:00.870 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: javax.net.ssl.SSLHandshakeException:
javax.net.ssl.SSLProtocolException: SSL handshake aborted:
ssl=0xb95dcb40: Failure in SSL library, usually a protocol error 06-25
10:13:00.874 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1
alert protocol version (external/openssl/ssl/s23_clnt.c:741
0x9dc27d4d:0x00000000) 06-25 10:13:00.886
2249-2249/com.example.waadalkatheri.retrofittraning W/System.err:
at
org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:436)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:302)
06-25 10:13:00.898 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: at
okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:270)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:162)
06-25 10:13:00.902 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: at
okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
06-25 10:13:00.910 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: 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)
06-25 10:13:00.926 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: at
okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
06-25 10:13:00.930 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: at
okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
06-25 10:13:00.934 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: at
okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
06-25 10:13:00.938 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: 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:200)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:147) 06-25 10:13:00.942 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: at
okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) 06-25
10:13:00.946 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: 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) 06-25 10:13:00.950 2249-2249/com.example.waadalkatheri.retrofittraning W/System.err:
Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted:
ssl=0xb95dcb40: Failure in SSL library, usually a protocol error 06-25
10:13:00.958 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1
alert protocol version (external/openssl/ssl/s23_clnt.c:741
0x9dc27d4d:0x00000000)
at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native
Method) 06-25 10:13:00.962
2249-2249/com.example.waadalkatheri.retrofittraning W/System.err:
at
org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:395)
... 23 more 06-25 10:13:00.974 2249-2249/com.example.waadalkatheri.retrofittraning V/TAG: no data
06-25 10:13:00.978 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: javax.net.ssl.SSLHandshakeException:
javax.net.ssl.SSLProtocolException: SSL handshake aborted:
ssl=0xb95fea28: Failure in SSL library, usually a protocol error 06-25
10:13:00.986 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1
alert protocol version (external/openssl/ssl/s23_clnt.c:741
0x9dc27d4d:0x00000000) 06-25 10:13:01.002
2249-2249/com.example.waadalkatheri.retrofittraning W/System.err:
at
org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:436)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:302)
06-25 10:13:01.006 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: at
okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:270)
06-25 10:13:01.010 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: at
okhttp3.internal.connection.RealConnection.connect(RealConnection.java:162)
06-25 10:13:01.014 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: 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)
06-25 10:13:01.018 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: 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) 06-25 10:13:01.022 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: 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)
06-25 10:13:01.026 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: at
okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:147) 06-25 10:13:01.030 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: 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)
Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb95fea28: Failure in SSL library, usually a protocol
error
error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version (external/openssl/ssl/s23_clnt.c:741
0x9dc27d4d:0x00000000)
at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native
Method)
at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:395)
06-25 10:13:01.034 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: ... 23 more 06-25 10:13:02.586
2249-2249/com.example.waadalkatheri.retrofittraning V/TAG: no data
06-25 10:13:02.586 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: javax.net.ssl.SSLHandshakeException:
javax.net.ssl.SSLProtocolException: SSL handshake aborted:
ssl=0xb95dcb40: Failure in SSL library, usually a protocol error 06-25
10:13:02.590 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1
alert protocol version (external/openssl/ssl/s23_clnt.c:741
0x9dc27d4d:0x00000000) 06-25 10:13:02.594
2249-2249/com.example.waadalkatheri.retrofittraning W/System.err:
at
org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:436)
06-25 10:13:02.598 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: at
okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:302)
06-25 10:13:02.602 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: at
okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:270)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:162)
06-25 10:13:02.606 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: 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)
06-25 10:13:02.610 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: 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)
06-25 10:13:02.614 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: at
okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93) 06-25 10:13:02.618 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: at
okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
06-25 10:13:02.622 2249-2249/com.example.waadalkatheri.retrofittraning
W/System.err: 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$AsyncCall.execute(RealCall.java:147)
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) 06-25 10:13:02.626 2249-2249/com.example.waadalkatheri.retrofittraning W/System.err:
Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted:
ssl=0xb95dcb40: Failure in SSL library, usually a protocol error
error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version (external/openssl/ssl/s23_clnt.c:741
0x9dc27d4d:0x00000000)
at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native
Method)
at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:395)
... 23 more
As seen here, your api https://api.github.com supports only TLS 1.2. Your test device might have an android version 16+ and TLS 1.2 is supported in API level 16+, but are not enabled by default.For 20+ devices it is enabled by default. So for 16<device<20 create a custom SSLSocketFactory with TLS 1.2 enabled like below
TLSSocketFactory.java
public class TLSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory delegate;
public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
delegate = context.getSocketFactory();
}
#Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
#Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
#Override
public Socket createSocket() throws IOException {
return enableTLSOnSocket(delegate.createSocket());
}
#Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}
#Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
#Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}
#Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
#Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if(socket != null && (socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.2"});
}
return socket;
}
}
Now create an OkHttpClient and add the client to retrofit like this
public void loadData (View view){
OkHttpClient client=new OkHttpClient();
try {
client = new OkHttpClient.Builder()
.sslSocketFactory(new TLSSocketFactory())
.build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
String LINK = "https://api.github.com";
Retrofit retrofit = new Retrofit.Builder ().client(client).baseUrl (LINK).build ();
GithubServise githubServise= retrofit.create (GithubServise.class);
githubServise.getGithub ().enqueue (new Callback<ResponseBody> () {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
textView.setText (response.body ().string ());
Log.v ("TAG","yes");
} catch (IOException e) {
e.printStackTrace ();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
textView.setText ("no data");
}
});
}
When onFailure gets called it means that the error was in the networking. So something in the conection is not working, maybe you have already checked these things..
Make sure you have internet conection and the url is correct by doing the same http request from your browser on your mobile (Chrome).
Check that in the manifest you have asked for the Internet permission:
uses-permission android:name="android.permission.INTERNET"
Related
I am building an app and it is working fine in Android 8
when I test it on older version I get the following crash
Android Version: 6.0.1
Device: samsung (SM-J500H)
Crash log
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:357)
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 com.sbs16.ensofia.network.manager.EnsofiaHttpLoggingInterceptor.intercept(EnsofiaHttpLoggingInterceptor.kt:46)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.sbs16.ensofia.network.manager.EnsofiaResponseInterceptor.intercept(EnsofiaResponseInterceptor.kt:7)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.sbs16.ensofia.network.manager.AuthorizationInterceptor.intercept(AuthorizationInterceptor.kt:61)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.sbs16.ensofia.network.manager.ConnectivityInterceptor.intercept(ConnectivityInterceptor.kt:16)
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)
Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:337)
at com.android.org.conscrypt.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:231)
at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:115)
at com.android.org.conscrypt.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:643)
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:353)
... 35 more
Caused by: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
... 41 more
can anyone help please?
If you use a self-signed certificate, Google don't accept this. You should use X.509.
When you request your server, first call the trustCerts method as defined below. Then, you can initiate a request.
#SuppressLint("TrulyRandom")
public static void trustCerts() {
try {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
#Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
#Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
} catch (Exception e) {
Log.e(TAG, "Could not trust certs:", e);
}
}
I'm retrieving data from an API. When I try to launch the app on an Android emulator running Android API 19 the request fails with the error below.
It work perfectly fine using other versions of the emulator (like Android API 27).
I changed the URL to target another API from a previous project and it works. So it seems the issue is with this specific API but I don't understand why, especially as when I pass the URL into the emulator's browser it works fine.
I've seen some people suggesting this is an issue with the computer's firewall, but there is no firewall enabled on mine.
Retrofit
interface SpaceXApi {
#GET("rockets")
fun getRockets(): Observable<MutableList<RocketDto>>
}
object SpaceXApiConstants {
const val BASE_URL = "https://api.spacexdata.com/v3/"
}
// Interceptor passed to OkHttpClient Builder
class ConnectivityInterceptor(private val context: Context) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
if (isConnected()) {
return chain.proceed(chain.request())
} else {
throw NoNetworkException()
}
}
}
Error
D/OkHttp: --> GET https://api.spacexdata.com/v3/rockets
D/OkHttp: <-- HTTP FAILED: java.net.ConnectException: Failed to connect to api.spacexdata.com/2606:4700:30::681f:5749:443
W/System.err: java.net.ConnectException: Failed to connect to api.spacexdata.com/2606:4700:30::681f:5749:443
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:247)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:165)
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 com.example.myproject.network.ConnectivityInterceptor.intercept(ConnectivityInterceptor.kt:13)
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:180)
at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:42)
at io.reactivex.Observable.subscribe(Observable.java:12090)
at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
at io.reactivex.Observable.subscribe(Observable.java:12090)
at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:578)
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.access$201(ScheduledThreadPoolExecutor.java:152)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.net.ConnectException: failed to connect to api.spacexdata.com/2606:4700:30::681f:5749 (port 443) after 20000ms: isConnected failed: EHOSTUNREACH (No route to host)
at libcore.io.IoBridge.isConnected(IoBridge.java:223)
at libcore.io.IoBridge.connectErrno(IoBridge.java:161)
12-02 17:44:40.445 4877-4877/com.example.myproject W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
at java.net.Socket.connect(Socket.java:843)
at okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.java:73)
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:245)
... 38 more
Caused by: libcore.io.ErrnoException: isConnected failed: EHOSTUNREACH (No route to host)
at libcore.io.IoBridge.isConnected(IoBridge.java:208)
... 45 more
Any solution?
Looks like a protocol issue : devices with API 19 and older don't use TLS 1.2 by default.
You can enable it with this :
ProviderInstaller.installIfNeededAsync(this, new ProviderInstaller.ProviderInstallListener() {
#Override
public void onProviderInstalled() {
}
#Override
public void onProviderInstallFailed(int i, Intent intent) {
Log.i(TAG, "Provider install failed (" + i + ") : SSL Problems may occurs");
}
});
This has to be called before your first call, so I usually call it in the OnCreate of the Application object.
For more information, you can check this link : https://quizlet.com/blog/working-with-tls-1-2-on-android-4-4-and-lower
I have a problem with this particular site: https://tastedive.com/read/api
If I do an HTTP request with HttpURLConnection, I get a normal HTML response (on Android this code needs to be in a separate thread and also put all the necessary tries and catches):
StringBuilder result = new StringBuilder();
URL url = new URL("https://tastedive.com/read/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
System.out.println(result.toString()); // shows normal HTML response
But if I do it with OkHttp, with this code...
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://tastedive.com/read/api")
.build();
client.newCall(request).enqueue(new okhttp3.Callback() {
#Override
public void onFailure(okhttp3.Call call, IOException e) {
Log.d("MY", "failure", e);
}
#Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} else {
System.out.println(response.body().string());
}
}
});
...I get this error in onFailure:
java.net.ConnectException: Failed to connect to tastedive.com/2606:4700:30::681c:3a5:443
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:242)
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: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:841)
Caused by: java.net.ConnectException: failed to connect to tastedive.com/2606:4700:30::681c:3a5 (port 443) after 10000ms: isConnected failed: ENETUNREACH (Network is unreachable)
at libcore.io.IoBridge.isConnected(IoBridge.java:223)
at libcore.io.IoBridge.connectErrno(IoBridge.java:161)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
at java.net.Socket.connect(Socket.java:843)
at okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.java:71)
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:240)
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: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:841)
Caused by: libcore.io.ErrnoException: isConnected failed: ENETUNREACH (Network is unreachable)
at libcore.io.IoBridge.isConnected(IoBridge.java:208)
at libcore.io.IoBridge.connectErrno(IoBridge.java:161)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
at java.net.Socket.connect(Socket.java:843)
at okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.java:71)
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:240)
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: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:841)
This OkHttp that I'm using is from Retrofit 2.4.0.
Happens on both the emulator and the real device, but only on Kitkat. Also note that the exception is thrown immediately, not only after 10000 ms.
I solved it! The real device was actually getting Javax.net.ssl.SSLHandshakeException, while the emulator was getting java.net.ConnectException. This StackOverflow discussion describes that there's a bug around TLS for pre-Lollipop devices.
Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error
So now I use this code from this answer: https://stackoverflow.com/a/50640113/9702500, it solves both the emulator exception and the device exception:
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
.supportsTlsExtensions(true)
.tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0)
.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,
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
CipherSuite.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
CipherSuite.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA)
.build();
OkHttpClient client = new OkHttpClient.Builder()
.connectionSpecs(Collections.singletonList(spec))
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://tastedive.com")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
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);
}
When my users login success, i do many request to syn my local database.
I do this with retrofit and user RxJava to zip the response.
But when i have a SocketTimeoutException my application crash, and i don't know why.
This is my code :
private fun syncData(): Single<Boolean> {
getProgressTextView().text = getString(R.string.synchronizing)
val list: List<Single<Boolean>> = Arrays.asList(DocumentTypeManager.getAndSave(retrofit),
HomeAccessibilitiesManager.getAndSave(retrofit),
StreetTypesManager.getAndSave(retrofit),
IncidentTypesManager.getAndSave(retrofit),
TaskTypesManager.getAndSave(retrofit, this),
PatientFunituresManager.getAndSave(retrofit, this),
HealthMutualsManager.getAndSave(retrofit))
return Single.zip(list, {
it.forEach {
if (!(it as Boolean)) {
return#zip false
}
}
return#zip true
})
}
an example of an object that get the httpRequest
object HomeAccessibilitiesManager : AnkoLogger {
fun getAndSave(retrofit: Retrofit): Single<Boolean> {
val t = retrofit.create(RestApi::class.java)
.getHomeAccessibilities()
return HttpRequestDataManager.getAndSave(t)
}
}
the manager that save my webService return in database
object HttpRequestDataManager : AnkoLogger {
inline fun <reified T : io.realm.RealmModel> getAndSave(single: Single<List<T>>): Single<Boolean> {
return Single.create { subscriber ->
single
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ list ->
executeTransaction {
list.saveAll()
}
debug { "success sync, with ${list.size} results" }
subscriber.onSuccess(true)
},
{
if (it != null) {
warn { it.message }
subscriber.onError(it)
} else {
subscriber.onError(Throwable("unknow error"))
}
}
)
}
}
}
and the RestApi
#GET("api/v1/home_accessibilities")
fun getHomeAccessibilities(): Single<List<RHomeAccessibilities>>
i also have an JWTInterceptor
class JwtInterceptor(val context: Context) : Interceptor, AnkoLogger {
override fun intercept(chain: Interceptor.Chain): Response {
val builder = chain.request().newBuilder()
if (UserManager.jwtToken.isNotEmpty()) {
builder.header("Authorization", String.format("%s %s", "Bearer", UserManager.jwtToken))
}
val response = chain.proceed(builder.build())
if (response.code() == 401 && UserManager.islogged) {
UserManager.logout()
executeTransaction {
debug { "deleting all database" }
it.deleteAll()
}
val intent = Intent(context, LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
context.startActivity(intent)
context.runOnUiThread { context.toast(context.getString(R.string.session_expired)) }
}
return response
}
}
and the logs :
05-22 09:31:25.771 21960-22425/com.sanilea.itineraire D/OkHttp: <-- HTTP FAILED: java.net.SocketTimeoutException: SSL handshake timed out
05-22 09:31:25.771 21960-21960/com.sanilea.itineraire W/HttpRequestDataManager: SSL handshake timed out
05-22 09:31:25.772 21960-21960/com.sanilea.itineraire W/System.err: io.reactivex.exceptions.UndeliverableException: java.net.SocketTimeoutException: SSL handshake timed out
05-22 09:31:25.774 21960-21960/com.sanilea.itineraire W/System.err: at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:349)
at io.reactivex.internal.operators.single.SingleCreate$Emitter.onError(SingleCreate.java:82)
at com.sanilea.itineraire.managers.StreetTypesManager$getAndSave$$inlined$getAndSave$1$2.accept(HttpRequestDataManager.kt:52)
at com.sanilea.itineraire.managers.StreetTypesManager$getAndSave$$inlined$getAndSave$1$2.accept(HttpRequestDataManager.kt:21)
at io.reactivex.internal.observers.ConsumerSingleObserver.onError(ConsumerSingleObserver.java:47)
at io.reactivex.internal.operators.single.SingleObserveOn$ObserveOnSingleObserver.run(SingleObserveOn.java:79)
at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:109)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
05-22 09:31:25.775 21960-21960/com.sanilea.itineraire W/System.err:
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
05-22 09:31:25.776 21960-21960/com.sanilea.itineraire W/System.err:
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
05-22 09:31:25.777 21960-21960/com.sanilea.itineraire W/System.err: Caused by: java.net.SocketTimeoutException: SSL handshake timed out
05-22 09:31:25.778 21960-21960/com.sanilea.itineraire W/System.err:
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:351)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:302)
at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:270)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:162)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
05-22 09:31:25.779 21960-21960/com.sanilea.itineraire W/System.err:
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)
05-22 09:31:25.780 21960-21960/com.sanilea.itineraire W/System.err:
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
05-22 09:31:25.781 21960-21960/com.sanilea.itineraire W/System.err:
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)
05-22 09:31:25.782 21960-21960/com.sanilea.itineraire W/System.err:
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
05-22 09:31:25.783 21960-21960/com.sanilea.itineraire W/System.err:
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
05-22 09:31:25.786 21960-21960/com.sanilea.itineraire W/System.err:
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:212)
05-22 09:31:25.787 21960-21960/com.sanilea.itineraire W/System.err:
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
05-22 09:31:25.790 21960-21960/com.sanilea.itineraire W/System.err:
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
05-22 09:31:25.791 21960-21960/com.sanilea.itineraire W/System.err:
at com.sanilea.itineraire.http.JwtInterceptor.intercept(JwtInterceptor.kt:36)
05-22 09:31:25.792 21960-21960/com.sanilea.itineraire W/System.err:
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)
05-22 09:31:25.793 21960-21960/com.sanilea.itineraire W/System.err:
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:180)
at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:42)
at io.reactivex.Observable.subscribe(Observable.java:10981)
at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
at io.reactivex.Observable.subscribe(Observable.java:10981)
at io.reactivex.internal.operators.observable.ObservableSingleSingle.subscribeActual(ObservableSingleSingle.java:35)
at io.reactivex.Single.subscribe(Single.java:2801)
at io.reactivex.internal.operators.single.SingleSubscribeOn$SubscribeOnObserver.run(SingleSubscribeOn.java:89)
at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
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:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
05-22 09:31:25.794 21960-21960/com.sanilea.itineraire W/System.err:
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
05-22 09:31:25.798 21960-22426/com.sanilea.itineraire D/OkHttp: <-- HTTP FAILED: java.net.SocketTimeoutException: SSL handshake timed out
05-22 09:31:25.802 21960-21965/com.sanilea.itineraire I/zygote: Do partial code cache collection, code=122KB, data=78KB
05-22 09:31:25.809 21960-21965/com.sanilea.itineraire I/zygote: After code cache collection, code=122KB, data=78KB
05-22 09:31:25.810 21960-21965/com.sanilea.itineraire I/zygote: Increasing code cache capacity to 512KB
The problem come from my emulator, it was totaly broken...