问题
微信文档描述
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"] = Referer
view!!.loadUrl(url, wvHead)
} else {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(intent)
}
true
} catch (e: Exception) {
false
}
}
完整程序
package com.wuzhao.ktt.wvtaste
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.wuzhao.ktt.R
import kotlin.system.exitProcess
class WebViewTaste : AppCompatActivity() {
private lateinit var wv: WebView
companion 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 = true
wv.webViewClient = webClient
wv.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"] = Referer
view!!.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)
}
}
}