我构建了一个包含 WKWebView 的应用程序,并且 Web 视图加载的网站支持多种语言。我怎样才能改变Accept-Language
WKWebView 中的标头,或其他 HTTP 标头?
我已经让它以某种方式工作,但只有获取请求才会有自定义标头。正如 jbelkins 在链接中回答的那样,来自 Gabriel Cartiers 对您的问题的评论,您将必须操纵请求并重新加载它。
我已经让它适用于像这样的 GET 请求:
(它在 xamarin 0> c# 中,但我想你会明白的)
我创建了一个私有字段
private bool _headerIsSet
每次在 deligate 方法中发出请求时我都会检查:
[Foundation.Export("webView:decidePolicyForNavigationAction:decisionHandler:")]
public void DecidePolicy(WKWebView webView, WKNavigationAction navigationAction, Action<WKNavigationActionPolicy> decisionHandler)
{
var request = navigationAction.Request;
// check if the header is set and if not, create a muteable copy of the original request
if (!_headerIsSet && request is NSMuteableUrlRequest muteableRequest);
{
// define your custom header name and value
var keys = new object[] {headerKeyString};
var values = new object[] {headerValueString};
var headerDict = NSDictionary.FromObjectsAndKeys(values, keys);
// set the headers of the new request to the created dict
muteableRequest.Headers = headerDict;
_headerIsSet = true;
// attempt to load the newly created request
webView.LoadRequest(muteableRequest);
// abort the old one
decisionHandler(WKNavigationActionPolicy.Cancel);
// exit this whole method
return;
}
else
{
_headerIsSet = false;
decisionHandler(WKNavigationActionPolicy.Allow);
}
}
正如我所说,这只适用于GET-要求。不知何故,POST-要求不包含身体数据原始请求的主体数据(request.Body 和 request.BodyStream 为 null),因此 muteableRequest(原始请求的可变副本)不会包含原始请求的主体数据。
我希望这会对您或其他遇到相同问题的人有所帮助。
Edit:根据您的需要,将“Accept-Language”设置为键
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)