如何在Swift中为iOS全局请求添加HTTP头

72qzrwbm  于 2023-10-21  发布在  iOS
关注(0)|答案(9)|浏览(158)
func webView(webView: WKWebView!, decidePolicyForNavigationAction navigationAction: WKNavigationAction!, decisionHandler: ((WKNavigationActionPolicy) -> Void)!) {
     var request = NSMutableURLRequest(URL: navigationAction.request.URL)
     request.setValue("value", forHTTPHeaderField: "key")
     decisionHandler(.Allow)
}

在上面的代码中,我想给请求添加一个header。我试过做navigationAction.request.setValue("IOS", forKey: "DEVICE_APP"),但它不工作。
无论如何请帮帮我。

j0pj023g

j0pj023g1#

很遗憾,你不能用WKWebView做到这一点。
它在webView:decidePolicyForNavigationAction:decisionHandler:中肯定不起作用,因为navigationAction.request是只读的,并且是不可更改的NSURLRequest示例。
如果我理解正确的话,WKWebView在一个单独的内容和网络进程中运行沙箱,至少在iOS上,没有办法拦截或更改它的网络请求。
如果您返回到UIWebView,就可以做到这一点。

vbkedwbf

vbkedwbf2#

有很多不同的方法可以做到这一点,我发现最简单的解决方案是子类化WKWebView并覆盖loadRequest方法。大概是这样的:

class CustomWebView: WKWebView {
    override func load(_ request: URLRequest) -> WKNavigation? {
        guard let mutableRequest: NSMutableURLRequest = request as? NSMutableURLRequest else {
            return super.load(request)
        }
        mutableRequest.setValue("custom value", forHTTPHeaderField: "custom field")
        return super.load(mutableRequest as URLRequest)
    }
}

然后简单地使用CustomWebView类,就像它是一个WKWebView一样。

编辑注解:正如@Stefan Arentz指出的那样,这只适用于第一个请求。
注意:某些字段不能被覆盖,也不会被更改。我还没有做过彻底的测试,但我知道,User-Agent字段不能被覆盖,除非你做一个特定的黑客(check here for an answer to that

htzpubme

htzpubme3#

我已经修改了Au Ris的答案,使用NavigationAction而不是NavigationResponse,就像jonny建议的那样。此外,这修复了随后调用相同URL的情况,并且您不必再跟踪当前URL。这只适用于GET请求,但如果必要的话,肯定可以适用于其他请求类型。

import UIKit
    import WebKit
    class ViewController: UIViewController, WKNavigationDelegate  {
        var webView: WKWebView?

        override func viewDidLoad() {
            super.viewDidLoad()
            webView = WKWebView(frame: CGRect.zero)
            webView!.navigationDelegate = self
            view.addSubview(webView!)
            // [...] set constraints and stuff

            // Load first request with initial url
            loadWebPage(url: "https://my.url")
        }

        func loadWebPage(url: URL)  {
            var customRequest = URLRequest(url: url)
            customRequest.setValue("true", forHTTPHeaderField: "x-custom-header")
            webView!.load(customRequest)
        }
    
        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping
        (WKNavigationActionPolicy) -> Void) {
            if navigationAction.request.httpMethod != "GET" || navigationAction.request.value(forHTTPHeaderField: "x-custom-header") != nil {
                // not a GET or already a custom request - continue
                decisionHandler(.allow)
                return
            }
            decisionHandler(.cancel)
            loadWebPage(url: navigationAction.request.url!)
        }
    }
ezykj2lf

ezykj2lf4#

有一些限制,但你可以做到。拦截委托函数webView:decidePolicyFornavigationResponse:decisionHandler:中的响应,如果url改变,通过传递decisionHandler(.cancel)取消它,并使用新的URLRequest重新加载webview,设置自定义头和拦截的url。每次URL更改时(例如,用户点击链接),则取消该请求并创建一个带有自定义标题的新请求。

import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate  {
    var webView: WKWebView?
    var loadUrl = URL(string: "https://www.google.com/")!

    override func viewDidLoad() {
        super.viewDidLoad()

        webView = WKWebView(frame: CGRect.zero)
        webView!.navigationDelegate = self
        view.addSubview(webView!)
        webView!.translatesAutoresizingMaskIntoConstraints = false
        webView!.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
        webView!.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
        webView!.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
        webView!.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true

        // Load first request with initial url
        loadWebPage(url: loadUrl)
    }

    func loadWebPage(url: URL)  {
        var customRequest = URLRequest(url: url)
        customRequest.setValue("some value", forHTTPHeaderField: "custom header key")
        webView!.load(customRequest)
    }

    // MARK: - WKNavigationDelegate

    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        guard let url = (navigationResponse.response as! HTTPURLResponse).url else {
            decisionHandler(.cancel)
            return
        }

        // If url changes, cancel current request which has no custom headers appended and load a new request with that url with custom headers
        if url != loadUrl {
            loadUrl = url
            decisionHandler(.cancel)
            loadWebPage(url: url)
        } else {
            decisionHandler(.allow)
        }
    }
}
jtoj6r0c

jtoj6r0c5#

为了向AJAX请求添加自定义头,我使用了两个三个技巧的组合。first在我的原生Swift代码和JavaScript之间提供了一个同步通信通道。second覆盖XMLHttpRequestsend()方法。third将覆盖注入到加载到我的WKWebView中的网页中。
所以,这个组合是这样的:
而不是
request.setValue(“value”,forHTTPHeaderField:“key”)

  • 在ViewController中:*
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt headerName: String, defaultText _: String?, initiatedByFrame _: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
  if headerName == "key" {
    completionHandler("value")
  } else {
    completionHandler(nil)
  }
}}
  • 在viewDidLoad中:*
let script = 
  "XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;"
  "XMLHttpRequest.prototype.send = function (body) {"
    "let value = window.prompt('key');"
    "this.setRequestHeader('key', value);"
    "this.realSend(body)"
  "};"
webView.configuration.userContentController.addUserScript(WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: true))
  • 这是测试HTML文件:*
<html>
<head>
  <script>
    function loadAjax() {
      const xmlhttp = new XMLHttpRequest()
      xmlhttp.onload = function() {
         document.getElementById("load").innerHTML = this.responseText
      }
      xmlhttp.open("GET", "/ajax")
      xmlhttp.send()
    }
  </script>
</head>
<body>
  <button onClick="loadAjax()">Change Content</button> <br />
  <pre id="load">load…</pre>
</body>
</html>

/ajax的调用会带来一个通用的echo,包括所有的请求头。这样我就知道任务完成了。

uinbv5nw

uinbv5nw6#

你应该这么做:策略是让WKNavigationDelegate取消请求,修改它的可变副本并重新启动它。if-else用于在请求已经具有所需的报头时允许请求继续;否则,您将陷入无休止的load / decidePolicy循环。
不知道是怎么回事,但是如果你在每个请求上都设置了header,就会发生奇怪的事情,所以为了获得最好的结果,只在你关心的域的请求上设置header。
这里的例子为请求header.domain.com设置了一个header字段,并允许所有其他没有header的请求:

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSURL * actionURL = navigationAction.request.URL;
    if ([actionURL.host isEqualToString:@"header.domain.com"]) {
        NSString * headerField = @"x-header-field";
        NSString * headerValue = @"value";
        if ([[navigationAction.request valueForHTTPHeaderField:headerField] isEqualToString:headerValue]) {
            decisionHandler(WKNavigationActionPolicyAllow);
        } else {
            NSMutableURLRequest * newRequest = [navigationAction.request mutableCopy];
            [newRequest setValue:headerValue forHTTPHeaderField:headerField];
            decisionHandler(WKNavigationActionPolicyCancel);
            [webView loadRequest:newRequest];
        }
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}
smdnsysy

smdnsysy7#

private var urlrequestCurrent: URLRequest?

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    //print("WEB decidePolicyFor navigationAction: \(navigationAction)")
    if let currentrequest = self.urlrequestCurrent {
        //print("currentrequest: \(currentrequest), navigationAction.request: \(navigationAction.request)")
        if currentrequest == navigationAction.request {
            self.urlrequestCurrent = nil
            decisionHandler(.allow)
            return
        }
    }

    decisionHandler(.cancel)

    var customRequest = navigationAction.request
    customRequest.setValue("myvaluefffs", forHTTPHeaderField: "mykey")
    self.urlrequestCurrent = customRequest
    webView.load(customRequest)
}
kmpatx3s

kmpatx3s8#

我的解决方案是复制请求并添加标头,然后再次加载它

if navigationAction.request.value(forHTTPHeaderField: "key") == nil {
        decisionHandler(.cancel)
        
        var req:URLRequest = navigationAction.request;
        req.addValue("value", forHTTPHeaderField: "key");
        webView.load(req);
    } else {
        decisionHandler(.allow)
    }
ohtdti5x

ohtdti5x9#

上面提到的解决方案似乎可以在iOS 14上工作,但在iOS < 14上,POST请求Body总是null,导致服务器端拒绝请求。事实证明,这是WKWebView和WebKit中的一个已知错误,导致navigationLink.Request.Body始终为nil!!非常令人沮丧和愚蠢的错误,从苹果迫使UIWebView迁移到不稳定的WKWebView!
无论如何,解决方案是你应该(在取消请求之前),通过运行JavaScript函数获取POST主体,然后将结果分配回navigationAction.Request(如果navigationAction.Request.Body为null),然后取消操作,并使用更新的navigationAction.Request再次请求:
解决方案在Xamarin中,但原生iOS非常接近。

[Foundation.Export("webView:decidePolicyForNavigationAction:decisionHandler:")]
    public async void DecidePolicy(WebKit.WKWebView webView, WebKit.WKNavigationAction navigationAction, Action<WebKit.WKNavigationActionPolicy> decisionHandler)
    {
        try
        {
            var url = navigationAction.Request.Url;

            // only apply to requests being made to your domain
            if (url.Host.ToLower().Contains("XXXXX"))
            {
                if (navigationAction.Request.Headers.ContainsKey((NSString)"Accept-Language"))
                {
                    var languageHeaderValue = (NSString)navigationAction.Request.Headers[(NSString)"Accept-Language"];

                    if (languageHeaderValue == Globalization.ActiveLocaleId)
                    {
                       decisionHandler.Invoke(WKNavigationActionPolicy.Allow);
                        return;
                    }
                    else
                    {
                        decisionHandler(WKNavigationActionPolicy.Cancel);
                        var updatedRequest = SetHeaders((NSMutableUrlRequest)navigationAction.Request);

                        // Temp fix for navigationAction.Request.Body always null on iOS < 14
                        // causing form not to submit correctly
                        updatedRequest = await FixNullPostBody(updatedRequest);

                        WebView.LoadRequest(updatedRequest);
                    }
                }
                else
                {
                    decisionHandler(WKNavigationActionPolicy.Cancel);

                    var updatedRequest = SetHeaders((NSMutableUrlRequest)navigationAction.Request);

                    // Temp fix for navigationAction.Request.Body always null on iOS < 14
                    // causing form not to submit correctly
                    updatedRequest = await FixNullPostBody(updatedRequest);

                    WebView.LoadRequest(updatedRequest);
                }
            }
            else
            {
                decisionHandler.Invoke(WKNavigationActionPolicy.Allow);
            }
        }
        catch (Exception ex)
        {
            Logger.LogException(ex);
            decisionHandler?.Invoke(WKNavigationActionPolicy.Allow);
        }
    }
}

    private async Task<NSMutableUrlRequest> FixNullPostBody(NSMutableUrlRequest urlRequest)
    {
        try
        {
            // if on iOS 14 and higher, don't do this
            //if (UIDevice.CurrentDevice.CheckSystemVersion(14, 0))
                //return urlRequest;

            // only resume on POST http methods
            if (urlRequest.HttpMethod.ToLowerSafe() != "post")
                return urlRequest;

            // if post body is already there, exit
            if(urlRequest.Body != null)
                return urlRequest;

            if (WebView == null)
                return urlRequest;

            // get body post by running javascript
            var body = await WebView.EvaluateJavaScriptAsync("$('form').serialize()");//.ConfigureAwait(true);

            if (body != null)
            {
                //urlRequest.Body = urlRequest.Body; // always null on iOS < 14
                var bodyString = body.ToString();

                if (!bodyString.IsNullOrEmpty())
                    urlRequest.Body = NSData.FromString(bodyString);
            }

        }
        //This method will throw a NSErrorException if the JavaScript is not evaluated successfully.
        catch (NSErrorException ex)
        {
            DialogHelper.ShowErrorAlert(Logger.HandleExceptionAndGetErrorMsg(ex));
        }
        catch (Exception ex)
        {
            DialogHelper.ShowErrorAlert(Logger.HandleExceptionAndGetErrorMsg(ex));
        }

        return urlRequest;
    }

private NSMutableUrlRequest SetHeaders(NSMutableUrlRequest urlRequest)
    {
        try
        {
            if (this.UsePOST)
            {
                urlRequest.HttpMethod = "POST";
                urlRequest.Body = postParameters.Encode(NSStringEncoding.UTF8, false);
            }

            var keys = new object[] { "Accept-Language" };
            var objects = new object[] { Globalization.ActiveLocaleId };

            var dictionnary = NSDictionary.FromObjectsAndKeys(objects, keys);

            if (urlRequest.Headers == null)
            {
                urlRequest.Headers = dictionnary;
            }
            else
            {
                NSMutableDictionary httpHeadersCopy = new NSMutableDictionary(urlRequest.Headers);

                httpHeadersCopy.Remove((NSString)"Accept-Language");
                httpHeadersCopy.Add((NSString)"Accept-Language", (NSString)Globalization.ActiveLocaleId);

                urlRequest.Headers = null;
                urlRequest.Headers = (NSDictionary)httpHeadersCopy;
            }
        }
        catch (Exception ex)
        {
            Logger.LogException(ex);
        }
        return urlRequest;
    }

相关问题