How to set custom HTTP headers to requests made by a WKWebView

I have built an app that includes a WKWebView, and the website that the web view loads supports multiple languages. How can I change the Accept-Language header in a WKWebView, or other HTTP headers for that matter?


I've got it working in a way, but only get requests will have the custom header. As jbelkins answered in the linked so from Gabriel Cartiers comment to your question, you will have to manipulate the request and load it anew.

I've got it working for GET-Requests like this:

(it's in xamarin 0> c#, but i think you will get the idea)

i've created a private field

private bool _headerIsSet

which i check every time a request is made in the deligate method:

[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);
        }
    }

As i said, this only works for GET-Requests. Somehow, POST-Requests don't contain the body data of the original request (request.Body and request.BodyStream are null), so the muteableRequest (which is a muteable copy of the original request) won't contain the body data of the original request.

I hope this will help you or others that approach the same problem.

Edit: For your needs, set "Accept-Language" as the key

链接地址: http://www.djcxy.com/p/91528.html

上一篇: 完全卷积网络的每像素softmax

下一篇: 如何将自定义HTTP标头设置为WKWebView发出的请求