我正在尝试给Webview客户端添加自定义的HTTP标头(用于授权)。在某些情况下,它似乎是有效的,我可以登录到一个网页而不需要输入用户名和密码,并且我被重定向到另一个页面。但当该页面调用其他资源以获取数据填充元素时,会抛出错误并调用OnReceivedHttpError。我得到的错误是401未经授权,当我查看IWebResourceRequest上的标头时,根本找不到授权标头。我错过了什么还是有人遇到同样的问题吗?
使用Xamarin Forms 2.3.3.180并针对API 21(Android 5.0 Lollipop)进行编译,使用Android 7.1 Nougat。
我已经在Postman中尝试添加请求标头,它完美地工作。
渲染器:
使用Xamarin Forms 2.3.3.180并针对API 21(Android 5.0 Lollipop)进行编译,使用Android 7.1 Nougat。
我已经在Postman中尝试添加请求标头,它完美地工作。
渲染器:
public class MyWebViewRenderer : WebViewRenderer
{
private MyWebViewClient _webViewClient;
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if(_webViewClient == null)
_webViewClient = new MyWebViewClient();
Control.SetWebViewClient(_webViewClient);
Control.LongClickable = false;
Control.HapticFeedbackEnabled = false;
Control.Settings.JavaScriptEnabled = true;
var data = Encoding.GetEncoding("ISO-8859-1").GetBytes("username:password");
var base64string = Base64.EncodeToString(data, Base64Flags.NoWrap);
var headers = new Dictionary<string, string>();
headers.Add("Authorization", $"Basic {base64string}")
Control.LoadUrl(Control.Url, headers);
}
}
WebViewClient:
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
WebView.SetWebContentsDebuggingEnabled(true);
var data = Encoding.GetEncoding("ISO-8859-1").GetBytes("username:password");
var base64string = Base64.EncodeToString(data, Base64Flags.NoWrap);
var headers = new Dictionary<string, string>();
headers.Add("Authorization", $"Basic {base64string}")
view.LoadUrl(url, headers);
return true;
}
public override WebResourceResponse ShouldInterceptRequest(WebView view, IWebResourceRequest urlResource)
{
//headers does not always contains authorization header, so let's add it.
if (!urlResource.RequestHeaders.ContainsKey("authorization") && !urlResource.RequestHeaders.ContainsKey("Authorization"))
{
var data = Encoding.GetEncoding("ISO-8859-1").GetBytes("username:password");
var base64string = Base64.EncodeToString(data, Base64Flags.NoWrap);
urlResource.RequestHeaders.Add("Authorization", $"{base64string}");
}
return base.ShouldInterceptRequest(view, urlResource);
}
public override void OnReceivedHttpError(WebView view, IWebResourceRequest request, WebResourceResponse errorResponse)
{
base.OnReceivedHttpError(view, request, errorResponse);
}