Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

React-Native fetch Network request failed on android #20976

Closed
totofe opened this issue Sep 5, 2018 · 8 comments
Closed

React-Native fetch Network request failed on android #20976

totofe opened this issue Sep 5, 2018 · 8 comments
Labels
Bug 🌐Networking Related to a networking API. Platform: Android Android applications. Resolution: Locked This issue was locked by the bot.

Comments

@totofe
Copy link

totofe commented Sep 5, 2018

Environment

React Native Environment Info:
System:
OS: macOS High Sierra 10.13.4
CPU: x64 Intel(R) Core(TM) i5-5350U CPU @ 1.80GHz
Memory: 47.66 MB / 8.00 GB
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 8.11.3 - /usr/local/bin/node
npm: 5.6.0 - /usr/local/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
SDKs:
iOS SDK:
Platforms: iOS 11.4, macOS 10.13, tvOS 11.4, watchOS 4.3
Android SDK:
Build Tools: 23.0.1, 26.0.1, 26.0.3, 28.0.2
API Levels: 23, 26, 28
IDEs:
Xcode: 9.4.1/9F2000 - /usr/bin/xcodebuild
npmPackages:
react: 16.4.1 => 16.4.1
react-native: 0.56.0 => 0.56.0
npmGlobalPackages:
create-react-native-app: 1.0.0
react-native-cli: 2.0.1

Description

I try to call a https webservice using fetch. The webservice uses a certificate to be able to connect.
I had the same problem with IOS. I solved the problem by adding in the file RCTHTTPRequestHandler.m this code :

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
  completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}

On Android, I have this message:

09-03 15:56:13.013 4811-5139/com.mweb_dmc D/SettingsInterface:  from settings cache , name = sound_effects_enabled , value = 0
09-03 15:56:13.015 4811-5319/com.mweb_dmc D/libc-netbsd: [getaddrinfo]: hostname=xxx.xxx.xx.xxx; servname=(null); netid=0; mark=0
    [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
09-03 15:56:13.015 4811-5319/com.mweb_dmc I/System.out: [CDS][DNS] getAllByNameImpl netId = 0
09-03 15:56:13.016 4811-5319/com.mweb_dmc D/libc-netbsd: [getaddrinfo]: hostname=xxx.xxx.xx.xxx; servname=(null); netid=0; mark=0
    [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
09-03 15:56:13.016 4811-5319/com.mweb_dmc I/System.out: [CDS]rx timeout:0
09-03 15:56:13.017 4811-5319/com.mweb_dmc I/System.out: [socket][20] connection /xxx.xxx.xx.xxx:1443;LocalPort=43588(0)
    [CDS]connect[/xxx.xxx.xx.xxx:1443]
09-03 15:56:13.017 4811-5319/com.mweb_dmc D/Posix: [Posix_connect Debug]Process com.mweb_dmc :1443 
09-03 15:56:13.113 4811-5319/com.mweb_dmc I/System.out: [CDS]port[43588]
    [socket][/192.168.1.91:43588] connected
09-03 15:56:13.114 4811-5319/com.mweb_dmc D/libc-netbsd: [getaddrinfo]: hostname=xxx.xxx.xx.xxx; servname=(null); netid=0; mark=0
    [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
09-03 15:56:13.115 4811-5319/com.mweb_dmc D/NativeCrypto: ssl=0xaf53cd00 NativeCrypto_SSL_do_handshake fd=0x96f1cd20 shc=0x96f1cd24 timeout_millis=0 client_mode=1 npn=0x0
    doing handshake ++
    ssl=0xaf53cd00 info_callback where=0x10 ret=1
    ssl=0xaf53cd00 handshake start in CINIT  before connect initialization
    ssl=0xaf53cd00 info_callback calling handshakeCompleted
    ssl=0xaf53cd00 info_callback completed
    ssl=0xaf53cd00 info_callback where=0x1001 ret=1
    ssl=0xaf53cd00 SSL_connect:CINIT  before connect initialization
    ssl=0xaf53cd00 info_callback ignored
    ssl=0xaf53cd00 info_callback where=0x1001 ret=1
    ssl=0xaf53cd00 SSL_connect:3WCH_A SSLv3 write client hello A
    ssl=0xaf53cd00 info_callback ignored
    ssl=0xaf53cd00 info_callback where=0x1002 ret=-1
    ssl=0xaf53cd00 SSL_connect:error exit in 3RSH_A SSLv3 read server hello A
    ssl=0xaf53cd00 info_callback ignored
    doing handshake -- ret=-1
    ssl=0xaf53cd00 NativeCrypto_SSL_do_handshake ret=-1 errno=11 sslError=2 timeout_millis=0
09-03 15:56:13.194 4811-5319/com.mweb_dmc D/NativeCrypto: doing handshake ++
    ssl=0xaf53cd00 info_callback where=0x1001 ret=1
    ssl=0xaf53cd00 SSL_connect:3RSH_A SSLv3 read server hello A
    ssl=0xaf53cd00 info_callback ignored
09-03 15:56:13.194 4811-5319/com.mweb_dmc E/NativeCrypto: ssl=0xaf53cd00 cert_verify_callback x509_store_ctx=0x96f1cb4c arg=0x0
    ssl=0xaf53cd00 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_RSA
09-03 15:56:13.196 4811-5319/com.mweb_dmc D/NativeCrypto: ssl=0xaf53cd00 cert_verify_callback => 0
09-03 15:56:13.196 4811-5319/com.mweb_dmc D/OpenSSLLib: OpensslErr:Module:16(190:126); file:external/boringssl/src/ssl/s3_clnt.c ;Line:984;Function:ssl3_get_server_certificate
09-03 15:56:13.196 4811-5319/com.mweb_dmc D/NativeCrypto: ssl=0xaf53cd00 info_callback where=0x4008 ret=558
    ssl=0xaf53cd00 SSL3 alert write:F:CU fatal certificate unknown
    ssl=0xaf53cd00 info_callback ignored
    ssl=0xaf53cd00 info_callback where=0x1002 ret=-1
    ssl=0xaf53cd00 SSL_connect:error exit in 3RSC_B SSLv3 read server certificate B
    ssl=0xaf53cd00 info_callback ignored
    doing handshake -- ret=-1
    ssl=0xaf53cd00 NativeCrypto_SSL_do_handshake exception => 0
09-03 15:56:13.197 4811-5319/com.mweb_dmc I/System.out: close [socket][/192.168.1.91:43588]
    close [socket][/:::43588]
09-03 15:56:13.304 4811-5138/com.mweb_dmc I/ReactNativeJS: { [Error: Error Connection]
      line: 119541,
      column: 24,
      sourceURL: 'http://localhost:8081/index.delta?platform=android&dev=true&minify=false' }

how can I solve this problem for android?

Reproducible Demo

return fetch('https://xxx.xxx.xx.xxx:1443/orawsv/ABLTEST/WSS_MWEB_LOGIN/GETLOGIN', {
    method: 'POST',
    mode: 'cors',
    headers: headers,
    credentials: 'include',
    body:  sr
  })
    .then((response) =>{
if(!response.ok){
        let error = new Error("Error Connection");
      throw error;
      }
})
    .catch((error) => {
      console.log(error);
}
) 
}

@react-native-bot react-native-bot added 🌐Networking Related to a networking API. Platform: Android Android applications. labels Sep 5, 2018
@git-Asir
Copy link

git-Asir commented Sep 13, 2018

##desc
when i update to react-native 0.57.1, I have a similar problem. Fetch cannot send HTTPS requests;but http is ok;
this problem found on android

##fetch error:
error:TypeError: Network request failed
YellowBox.js:67 Possible Unhandled Promise Rejection (id: 0):
TypeError: Network request failed
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (blob:http://localhost:8081/ef8b9a53-d930-4e4f-8e2b-9ad73681b847:20611:18)
at XMLHttpRequest.dispatchEvent (blob:http://localhost:8081/ef8b9a53-d930-4e4f-8e2b-9ad73681b847:23187:27)
at XMLHttpRequest.setReadyState (blob:http://localhost:8081/ef8b9a53-d930-4e4f-8e2b-9ad73681b847:22942:20)
at XMLHttpRequest.__didCompleteResponse (blob:http://localhost:8081/ef8b9a53-d930-4e4f-8e2b-9ad73681b847:22769:16)
at blob:http://localhost:8081/ef8b9a53-d930-4e4f-8e2b-9ad73681b847:22879:47
at RCTDeviceEventEmitter.emit (blob:http://localhost:8081/ef8b9a53-d930-4e4f-8e2b-9ad73681b847:3282:37)
at MessageQueue.__callFunction (blob:http://localhost:8081/ef8b9a53-d930-4e4f-8e2b-9ad73681b847:2775:44)
at blob:http://localhost:8081/ef8b9a53-d930-4e4f-8e2b-9ad73681b847:2548:17
at MessageQueue.__guard (blob:http://localhost:8081/ef8b9a53-d930-4e4f-8e2b-9ad73681b847:2729:13)
at MessageQueue.callFunctionReturnFlushedQueue (blob:http://localhost:8081/ef8b9a53-d930-4e4f-8e2b-9ad73681b847:2547:14)
console.warn @ YellowBox.js:67
onUnhandled @ Promise.js:43
onUnhandled @ rejection-tracking.js:71
(anonymous) @ JSTimers.js:256
_callTimer @ JSTimers.js:152
callTimers @ JSTimers.js:405
__callFunction @ MessageQueue.js:349
(anonymous) @ MessageQueue.js:106
__guard @ MessageQueue.js:297
callFunctionReturnFlushedQueue @ MessageQueue.js:105
(anonymous) @ debuggerWorker.js:72

##React Native Environment Info:
System:
OS: macOS High Sierra 10.13.3
CPU: x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
Memory: 513.66 MB / 8.00 GB
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 8.10.0 - /usr/local/bin/node
Yarn: 1.5.1 - /usr/local/bin/yarn
npm: 6.1.0 - /usr/local/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
SDKs:
iOS SDK:
Platforms: iOS 11.3, macOS 10.13, tvOS 11.3, watchOS 4.3
Android SDK:
Build Tools: 23.0.1, 23.0.3, 25.0.0, 25.0.1, 25.0.2, 25.0.3, 26.0.1, 26.0.2, 26.0.3, 27.0.1, 27.0.3
API Levels: 19, 23, 24, 25, 26, 27
IDEs:
Android Studio: 3.0 AI-171.4443003
Xcode: 9.3/9E145 - /usr/bin/xcodebuild
npmPackages:
react: ^16.4.1 => 16.5.0
react-native: ^0.57.0 => 0.57.0
npmGlobalPackages:
react-native-cli: 2.0.1
react-native-update-cli: 0.1.0

@anshumanburman
Copy link

@asir ... i am facing the same issue . please let me know if you resolved this issue.

@totofe
Copy link
Author

totofe commented Oct 1, 2018

I do not know if it's optimized, but I solved the problem with this code:

in MainApplication.java

`@Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
    OkHttpClientProvider.setOkHttpClientFactory(new CustomClientFactory());
  }`

In CustomClientFactory.java

`import android.util.Log;

import com.facebook.react.modules.network.OkHttpClientFactory;
import com.facebook.react.modules.network.OkHttpClientProvider;
import com.facebook.react.modules.network.ReactCookieJarContainer;

import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.net.*;
import java.io.*;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.*;

public class CustomClientFactory implements OkHttpClientFactory {
        private static final String TAG = "OkHttpClientFactory";

    @Override
    public OkHttpClient createNewNetworkModuleClient() {
            try {
                // Create a trust manager that does not validate certificate chains
                final TrustManager[] trustAllCerts = new TrustManager[]{
                        new X509TrustManager() {
                            @Override
                            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                            }

                            @Override
                            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                            }

                            @Override
                            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                                return new java.security.cert.X509Certificate[]{};
                            }
                        }
                };

                // Install the all-trusting trust manager
                final SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                // Create an ssl socket factory with our all-trusting manager
                final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();


                ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                        .tlsVersions(TlsVersion.TLS_1_1)
                        .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_PSK_WITH_AES_128_CBC_SHA,
                                CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256)
                        .build();

                List<ConnectionSpec> specs = new ArrayList<>();
                specs.add(spec);
                specs.add(ConnectionSpec.COMPATIBLE_TLS);
                specs.add(ConnectionSpec.CLEARTEXT);

                OkHttpClient.Builder builder = new OkHttpClient.Builder().connectionSpecs(specs)
                                .connectTimeout(0, TimeUnit.MILLISECONDS).readTimeout(0, TimeUnit.MILLISECONDS)
                                .writeTimeout(0, TimeUnit.MILLISECONDS).cookieJar(new ReactCookieJarContainer());
                builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
                builder.hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });

                OkHttpClient okHttpClient = builder.build();
                return okHttpClient;
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
                throw new RuntimeException(e);
            }
        }
}
`

@devtechvalens
Copy link

@totofe - Its not working

@git-Asir
Copy link

git-Asir commented Jan 1, 2019

@anshumanburman @18601673727 when i update to react-native 0.57.1,the https is not work,but http is ok;
i found 0.57.1 the target sdk is changed;
#21088 (comment)

@adrispo
Copy link

adrispo commented Feb 7, 2019

I do not know if it's optimized, but I solved the problem with this code:

in MainApplication.java

`@Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
    OkHttpClientProvider.setOkHttpClientFactory(new CustomClientFactory());
  }`

In CustomClientFactory.java

`import android.util.Log;

import com.facebook.react.modules.network.OkHttpClientFactory;
import com.facebook.react.modules.network.OkHttpClientProvider;
import com.facebook.react.modules.network.ReactCookieJarContainer;

import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.net.*;
import java.io.*;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.*;

public class CustomClientFactory implements OkHttpClientFactory {
        private static final String TAG = "OkHttpClientFactory";

    @Override
    public OkHttpClient createNewNetworkModuleClient() {
            try {
                // Create a trust manager that does not validate certificate chains
                final TrustManager[] trustAllCerts = new TrustManager[]{
                        new X509TrustManager() {
                            @Override
                            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                            }

                            @Override
                            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                            }

                            @Override
                            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                                return new java.security.cert.X509Certificate[]{};
                            }
                        }
                };

                // Install the all-trusting trust manager
                final SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                // Create an ssl socket factory with our all-trusting manager
                final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();


                ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                        .tlsVersions(TlsVersion.TLS_1_1)
                        .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_PSK_WITH_AES_128_CBC_SHA,
                                CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256)
                        .build();

                List<ConnectionSpec> specs = new ArrayList<>();
                specs.add(spec);
                specs.add(ConnectionSpec.COMPATIBLE_TLS);
                specs.add(ConnectionSpec.CLEARTEXT);

                OkHttpClient.Builder builder = new OkHttpClient.Builder().connectionSpecs(specs)
                                .connectTimeout(0, TimeUnit.MILLISECONDS).readTimeout(0, TimeUnit.MILLISECONDS)
                                .writeTimeout(0, TimeUnit.MILLISECONDS).cookieJar(new ReactCookieJarContainer());
                builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
                builder.hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });

                OkHttpClient okHttpClient = builder.build();
                return okHttpClient;
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
                throw new RuntimeException(e);
            }
        }
}
`

This worked for me on android! Thanks!

@dulmandakh
Copy link
Contributor

this is fixed in the master, and will be included in future releases. for work arounds see #23984

@Temirtator
Copy link

One of the problem for this bug may be, that API have some restricted characters in URL, like underscore. Look at link below
https://stackoverflow.com/questions/27048949/http-post-in-android-with-underscore-in-url

@facebook facebook locked as resolved and limited conversation to collaborators Mar 19, 2020
@react-native-bot react-native-bot added the Resolution: Locked This issue was locked by the bot. label Mar 19, 2020
# for free to subscribe to this conversation on GitHub. Already have an account? #.
Labels
Bug 🌐Networking Related to a networking API. Platform: Android Android applications. Resolution: Locked This issue was locked by the bot.
Projects
None yet
Development

No branches or pull requests

9 participants