【问题标题】:Using Swift to handle GZipped (containing JSON) HTTP response使用 Swift 处理 GZipped(包含 JSON)HTTP 响应
【发布时间】:2015-05-07 08:54:43
【问题描述】:

我编写了从 HTTP 响应中获取 GZipped Json 数据的 Android 应用程序。现在我想写一些做同样事情的 iPhone 应用程序。

使用 Swift 处理 GZipped Json 数据需要哪些类和方法?

【问题讨论】:

  • 你能显示http响应的头部吗?如果标头包含“Content-Encoding: gzip”,则数据将使用 NSURLConnection.sendAsynchronousRequest 自动解码。
  • 是的,内容编码是 GZip。我可以控制响应,因为它是我自己的服务器,已经被调用的 PHP 脚本。谢谢

标签: json swift http


【解决方案1】:

快速方面:

  • 解码 gzip - 对于网络,您可以使用 Alamofire。这个很 众所周知并且基于 NSURLConnection / NSURLSession 所以也 自动支持 gzipped 编码响应。 (我试过并测试了它,它不需要任何额外的代码就可以工作)。要检查 php 响应是否真的被 gzip 压缩,请打印响应变量(alamofire 完成处理程序中的第二个变量) 到控制台。这将打印响应头......它应该 包含以下内容:“内容编码:gzip”。
  • 编码为 gzip - 如果您还想从您的 iOS App to PHP(您发布到 php 文件的参数) 看看here

在 php 方面:

  • 解码 gzip - 要解压缩收到(gzip 压缩)的帖子数据(来自您的 iOS 应用),请使用:

    // Read the post data
    $handle = fopen("php://input", "rb");
    $raw_post_data = '';
    while (!feof($handle)) {
       $raw_post_data .= fread($handle, 8192);
    }
    fclose($handle);
    
    // unzip the post data
    $raw_post_data_unzipped = gzdecode($raw_post_data);
    
  • 编码到 gzip - 要发送 gzip 后的响应(到您的 iOS 应用),请在 php 文件开头的某处添加以下行。

    ob_start('ob_gzhandler');
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-15
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    相关资源
    最近更新 更多