Can't set headers on my WKWebView POST request

前端 未结 7 1348
花落未央
花落未央 2020-12-04 12:50

I want to do a POST request to my WKWebView but the headers doesn\'t get set when I monitor the requests with Charles so the request fails. What is wrong here?<

相关标签:
7条回答
  • 2020-12-04 13:31

    As the OP stated, I have also confirmed in Charles that the body is 0 bytes after webView.load(request).

    There's a workaround for this WKWebView bug, we will initiate a POST request using URLSession convert the data returned by the server to String and instead of loading the url we will use loadHTMLString which will:

    Set the webpage contents and base URL.

    and the content is our converted string:

    var request = URLRequest(url: URL(string: "http://www.yourWebsite")!)
    request.httpMethod = "POST"
    let params = "do=something&andAgain=something"
    request.httpBody = params.data(using: .utf8)
    
    let task = URLSession.shared.dataTask(with: request) { (data : Data?, response : URLResponse?, error : Error?) in
            if data != nil {
                if let returnString = String(data: data!, encoding: .utf8) {
                    self.webView.loadHTMLString(returnString, baseURL: URL(string: "http://www.yourWebsite.com")!)
                }
            }
    }
    task.resume()
    
    0 讨论(0)
提交回复
热议问题