The solution to net::ERR_CLEARTEXT_NOT_PERMITTED and net::ERR_CONNECTION_REFUSED when the back-end program is running locally and accessed with the android emulator

1 When the net::ERR_CLEARTEXT_NOT_PERMITTED problem occurs, it is because starting from Android 9.0 (API level 28), cleartext support is disabled by default. Therefore, none of the http urls can be loaded in the webview. The solution is to add it under the application tag in the manifest file.

 <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.KotlinAndH5"
        android:usesCleartextTraffic="true"
        。。。。。。。

2 When net::ERR_CONNECTION_REFUSED appears, it may be because the ip address accessed in your main program is incorrect, and the host number accessed by the computer browser is localhost or 127.0.0.1. But you need to use 10.0.2.2 on the phone simulator

package com.njupt.kotlinandh5

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient

class MainActivity : AppCompatActivity() {
    
    

    private val myWebView by lazy {
    
    
        findViewById<WebView>(R.id.mWebView)
    }
    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //1开启kotlin与H5通信的开关
        myWebView.settings.javaScriptEnabled=true
        myWebView.webViewClient=MyWebViewClient()
        myWebView.webChromeClient=MyWebChromeClient()
        myWebView.loadUrl("http://10.0.2.2:8080/bmi/")
    }
    private class MyWebViewClient:WebViewClient(){
    
    
        //界面加载完成之后会调用这个方法
        override fun onPageFinished(view: WebView?, url: String?) {
    
    
            super.onPageFinished(view, url)
        }

    }

    private class MyWebChromeClient:WebChromeClient(){
    
    
        //加载进度条
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
    
    
            super.onProgressChanged(view, newProgress)
        }

    }
}

Guess you like

Origin blog.csdn.net/m0_56184347/article/details/130204189