问题
微信文档描述
https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_4
解决方法
文档说明白了,要在请求头上加上Refrence,
注意并不是在加载webview时加上请求头,
而是在调用微信支付的时候加上这个请求头
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {return try {if (url!!.startsWith("http:") || url.startsWith("https:")) {val wvHead: MutableMap<String, String> = HashMap()wvHead["Referer"] = Refererview!!.loadUrl(url, wvHead)} else {val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))startActivity(intent)}true} catch (e: Exception) {false}}
完整程序
package com.wuzhao.ktt.wvtasteimport android.annotation.SuppressLintimport android.content.Intentimport android.net.Uriimport android.os.Bundleimport android.util.Logimport android.view.KeyEventimport android.webkit.WebViewimport android.webkit.WebViewClientimport androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport com.wuzhao.ktt.Rimport kotlin.system.exitProcessclass WebViewTaste : AppCompatActivity() {private lateinit var wv: WebViewcompanion object {// 定义WebView首页地址[伴生对象]const val WEB_URL = "你的webview url"const val Referer = "申请的地址"}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_web_view_taste)initWv()}@SuppressLint("SetJavaScriptEnabled")fun initWv() {wv = findViewById<WebView>(R.id.wv)wv.settings.javaScriptEnabled = truewv.webViewClient = webClientwv.loadUrl(WEB_URL)}private val webClient = object : WebViewClient() {override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {return try {if (url!!.startsWith("http:") || url.startsWith("https:")) {val wvHead: MutableMap<String, String> = HashMap()wvHead["Referer"] = Refererview!!.loadUrl(url, wvHead)} else {val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))startActivity(intent)}true} catch (e: Exception) {false}}}override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {return if ((keyCode == KeyEvent.KEYCODE_BACK)) {if (wv.canGoBack()) {wv.goBack()//返回上一页面true} else {AlertDialog.Builder(this@WebViewTaste).setTitle("退出") //设置对话框标题.setMessage("确定要退出?") //设置显示的内容.setPositiveButton("确定") { _, _ ->exitProcess(0)//退出程序}.setNegativeButton("取消") { _, _ ->}.show()false}} else {super.onKeyDown(keyCode, event)}}}

