React-native fetch() from https server with self-signed certificate

前端 未结 7 1286
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 01:39

I\'m trying to communicate with https server having self-signed certificate.

I can do this from .NET application (using ServicePointManager.ServerCertificateValidati

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 02:29

    Just to add information for users looking for Android Solution. As react-native do not handle SSL Error by default. There is a simple approach to Run your WebView for the websites that must be connected through "https" instead of "http".

    I am assuming you have already installed the react-native-webview module using NPM if no then please google.

    Once you have "react-native-webview" module inside "node_modules" folder. Go inside ".\node_modules >> react-native-webview >> android >> src >> main >> java >> com >> reactnativecommunity >> webview"

    Open "RNCWebViewManager.java" File in Text Editor and Add Below Code

    In import section add these two dependencies

    ....
    import android.webkit.SslErrorHandler;
    import android.net.http.SslError;
    ....
    

    Now Search for Below "class" inside same file protected static class RNCWebViewClient extends WebViewClient

    And add this method

    @Override
    public void onReceivedSslError(WebView webView, SslErrorHandler handler, SslError 
    error) {
        if (error.toString() == "piglet")
            handler.cancel();
        else
            handler.proceed(); // Ignore SSL certificate errors
    }
    

    Next Save the file and Build your Project. It would not show Blank page now and handle the Invalid SSL Error.

    Note:

    1. Solution works only if you are using "WebView" from "react-native-webview" instead of deprecated "WebView" from "react-native"
    2. Make sure you have already linked your "react-native" with "react-native-webview" else it would not be included inside your android project
    3. There might be version Error in "RNCWebViewModule", "RNCWebViewManager", "RNCWebViewFileProvider" classes (will be visible once you properly build your project using react-native run-android inside AndroidStudio after opening your android project using import) that you can easily fix using AndroidStudio

提交回复
热议问题