(Swift)如何检查内容编码是否为gzip
Swift中是否有任何方法可以确定来自请求的数据是否返回gzip 我想编写一个测试方法来检查内容编码是否返回gzip文件:(Swift)如何检查内容编码是否为gzip,swift,http,gzip,Swift,Http,Gzip,Swift中是否有任何方法可以确定来自请求的数据是否返回gzip 我想编写一个测试方法来检查内容编码是否返回gzip文件: 如果读取文件的前4个字节,则应获得 因此,您应该能够执行以下操作: var magicNumber = [UInt](count: 4, repeatedValue: 0) data.getBytes(&magicNumber, length: 4 * sizeof(UInt)) 如果它是gzip,它将有一个神奇的数字1f8b,所以检查一下 您可以从HTTPURL
如果读取文件的前4个字节,则应获得 因此,您应该能够执行以下操作:
var magicNumber = [UInt](count: 4, repeatedValue: 0)
data.getBytes(&magicNumber, length: 4 * sizeof(UInt))
如果它是gzip,它将有一个神奇的数字1f8b,所以检查一下 您可以从
HTTPURLResponse
中的标题字段中获取此信息:
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let response = response as? HTTPURLResponse {
if let encoding = response.allHeaderFields["Content-Encoding"] as? String {
print(encoding)
print(encoding == "gzip")
}
}
}.resume()
请注意,这将下载标题和数据
如果只想获取标题而不下载数据,更好的解决方案是使用URLRequest
设置为“HEAD”
,如下所示:
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
URLSession.shared.dataTask(with: request) { (_, response, _) in
if let response = response as? HTTPURLResponse {
if let enc = response.allHeaderFields["Content-Encoding"] as? String {
print(enc)
print(enc == "gzip")
}
}
}.resume()
这样,只下载标题