Mutable NSHTTPURLResponse or NSURLResponse

后端 未结 4 1677
一生所求
一生所求 2021-01-14 09:44

I need to modify response headers in an NSURLResponse. Is this possible?

4条回答
  •  花落未央
    2021-01-14 10:20

    You can do that, and you'd need NSHTTPURLResponse not NSURLResponse, because, in Swift, NSURLResponse can be used with many protocols rather than just http, such as ftp, data:, or https. As a result, you can call it to get the meta data info, such as expected content type, mime type and text encoding, while NSHTTURLResponse is the one responsible of handling HTTP protocol responses. Thus, it is the one to manipulate the headers.

    This is a small code that manipulates the header key Server from the response, and prints the value before and after the change.

    let url = "https://www.google.com"
        let request = NSMutableURLRequest(URL: NSURL(string: url)!)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
    
            if let response = response {
    
                let nsHTTPURLResponse = response as! NSHTTPURLResponse
                var headers = nsHTTPURLResponse.allHeaderFields
                print ("The value of the Server header before is: \(headers["Server"]!)")
                headers["Server"] = "whatever goes here"
                print ("The value of the Server header after is: \(headers["Server"]!)")
    
            }
    
            })
            task.resume()
    

提交回复
热议问题