elParaguayo
elParaguayo

Reputation: 1318

Can't serve http with WebViewAssetLoader - net:ERR_NAME_NOT_RESOLVED

I'm trying to develop an app that uses a WebView to connect to some services on my local network. Those services are all unsecured and so my web page connects to them via http://... and ws://.

Originally I had the webview loading files locally with file:// but I got CORS errors and, from my searching, I can see that I should use WebViewAssetLoader instead.

The issue I'm running into with this is that the loader only seems to serve the page over https. As I result, I then hit an error when trying to connect to an unsecure websocket:

"Mixed Content: The page at 'https://appassets.androidplatform.net/assets/index.html' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://my-server-ip'. This request has been blocked; this endpoint must be available over WSS."

Some of these services don't offer wss but it also feels unnecessary given this is only ever going to be run on my local network.

However, if I do myWebView.loadUrl("http://appassets.androidplatform.net/assets/index.html") then the page doesn't load and I just get an error page saying net:ERR_NAME_NOT_RESOLVED

So, is it possible for the WebViewAssetLoader to serve pages via http?

The MainActivity.kt file looks like this:

    class MainActivity : ComponentActivity() {

    @OptIn(ExperimentalTvMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout)
        val myWebView: WebView = findViewById(R.id.webview)
        // Setup asset loader to handle local asset paths
        val assetLoader = WebViewAssetLoader.Builder()
            .addPathHandler("/assets/", WebViewAssetLoader.AssetsPathHandler(this))
            .build();

        // This was needed to fix the mime type for javascript files
        myWebView.webViewClient = object : WebViewClient() {
            override fun shouldInterceptRequest(
                view: WebView,
                request: WebResourceRequest
            ): WebResourceResponse? {
                val interceptedWebRequest = assetLoader.shouldInterceptRequest(request.url)
                interceptedWebRequest?.let {
                    if (request.url.toString().endsWith("js", true)) {
                        it.mimeType = "text/javascript"
                    }
                }
                return interceptedWebRequest
            }

        }
        myWebView.settings.javaScriptEnabled = true
        myWebView.loadUrl("https://appassets.androidplatform.net/assets/index.html")

    }

}

The manifest file includes android:usesCleartextTraffic="true" but that had no impact.

Upvotes: 0

Views: 22

Answers (0)

Related Questions