【问题标题】:(Swift) How to check if content-encoding is gzip(Swift) 如何检查内容编码是否为 gzip
【发布时间】:2016-11-10 09:19:33
【问题描述】:

在 Swift 中有什么方法可以查明请求中的数据是否以 gzip 的形式返回?

我想写一个测试方法来检查Content-Encoding是否返回gzip文件:

【问题讨论】:

    标签: swift http gzip


    【解决方案1】:

    您可以从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()
    

    这样,只下载标题。

    【讨论】:

      【解决方案2】:

      如果你读取文件的前 4 个字节,你应该得到一个Magic Number

      所以你应该能够做这样的事情:

      var magicNumber = [UInt](count: 4, repeatedValue: 0)
      data.getBytes(&magicNumber, length: 4 * sizeof(UInt))
      

      如果它是 GZipped,它的幻数将为 1f 8b,因此请检查它。

      【讨论】:

        猜你喜欢
        • 2015-01-17
        • 2018-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-11
        • 2015-10-26
        相关资源
        最近更新 更多