iOS与服务器端 GZip压缩问题

摘要:
昨天搞了一天的GZip压缩,试了三种方式,一开始都不成功。今天就总结一下,写写iOS与Java服务器获取压缩数据的方法吧。

昨天搞了一天的GZip压缩,试了三种方式(libz库,ZipArchive,ASIHttpRequest),一开始都不成功。
理论上三个应该都能用的,但我都不行。等我试到第三种方式的时候才知道,不是我的问题,而是后台的问题(Java端输出方式一会再说)。
今天就总结一下,写写iOS与Java服务器获取压缩数据的方法吧。
一、客户端-服务端数据压缩解压流程(ASIHttpRequest)客户端生成request,
设置header允许使用压缩("Accept-Encoding","gzip"),即是告诉服务器,
客户端支持压缩,但凡可以压缩的服务器,尽管来吧!服务器收到这个header,
如果它支持压缩,可以通过压缩方式输出数据,
然后再写入response的header("Content-Encoding","gzip")
1.以ASIHttpRequest为例,代码如下:

NSURL* requestURL = [NSURL URLWithString:_listURL];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:requestURL];

// 默认为YES, 你可以设定它为NO来禁用gzip压缩 [request setAllowCompressedResponse:YES];

  [request setDelegate:self]; 
  [request startAsynchronous]; 

如果是普通的URLRequest,只要: request.setHeader("Accept-Encoding","gzip");
2.服务器端返回: response.setHeader("Content-Encoding","gzip");

3.客户端响应,同样以ASIHttpRequest为例(此例传输的是json数据,我还使用了SBJson解析一下):

  - (void)requestFinished:(ASIHTTPRequest *)request{ 
        NSString *jsonString = @""; 
        SBJsonParser* jsonParser = [[SBJsonParser alloc] init];
        NSMutableDictionary *jsonDictionary = nil; 
        BOOL dataWasCompressed = [request isResponseCompressed]; // 响应是否被gzip压缩过?
        if (dataWasCompressed) 
            { 
                NSData *uncompressedData = [request responseData]; 
                // 解压缩后的数据 
                NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); 
                jsonString = [[NSString alloc]initWithData:uncompressedData encoding:enc]; 
                jsonDictionary = [jsonParser objectWithString:jsonString error:nil]; 
                [jsonString release];
            }else { 
                jsonString = [request responseString]; 
                jsonDictionary = [jsonParser objectWithString:jsonString error:nil]; 
            } 
                self._tableDict = jsonDictionary; 
                [jsonParser release]; 
                [self loadTableDict]; 
                [self release]; 
} 

附上一篇非常详细的ASIHttpRequest请求Json数据教程(无GZip相关内容):
http://ios-blog.co.uk/articles/tutorials/parsing-json-on-ios-with-asihttprequest-and-sbjson/
libz库 libz库是官方的一个库,貌似ASIHttpRequest也是用这个库解压的,当我们获得压缩过的data数据以后(方法与上面类似,
只是获得了普通的data数据响应),可以使用这种方法解压数据,解压方法如下所示(如果仅仅放在当前类下面使用,传个data参数进来,
然后把self换成变量名):

#include @implementation NSData (DDData) 
  - (NSData *)gzipInflate { 
      if ([self length] == 0) 
         return self; 
         unsigned full_length = [self length]; 
         unsigned half_length = [self length] / 2;
         NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length]; BOOL done = NO; 
         int status; 
         z_stream strm; 
         strm.next_in = (Bytef *)[self bytes]; 
         strm.avail_in = [self length]; 
         strm.total_out = 0; 
         
         strm.zalloc = Z_NULL; 
         strm.zfree = Z_NULL; 
         if (inflateInit2(&strm, (15+32)) != Z_OK) return nil; 
         
         while (!done) { // Make sure we have enough room and reset the lengths. 
            if (strm.total_out >= [decompressed length])
            [decompressed increaseLengthBy: half_length];
            
            strm.next_out = [decompressed mutableBytes] + strm.total_out;
            strm.avail_out = [decompressed length] - strm.total_out; 
            // Inflate another chunk. status = inflate (&strm, Z_SYNC_FLUSH); 
            if (status == Z_STREAM_END) 
                done = YES; 
                else if (status != Z_OK) 
                break;
          } 
         if (inflateEnd (&strm) != Z_OK) return nil;
         // Set real length. 
         if (done) {
            [decompressed setLength: strm.total_out]; 
            return [NSData dataWithData: decompressed];
         } else
    return nil; 
} 

附上一篇非常详细的libz库压缩教程 http://www.clintharris.net/2009/how-to-gzip-data-in-memory-using-objective-c/

以及压缩解压教程(代码从这里拷贝的): http://deusty.blogspot.com/2007/07/gzip-compressiondecompression.html

ZipArchive 上面讲的都是Memory压缩与解压,ZipArchive主要是对文档进行处理。昨天在上述方法不成功的情况下,我把获取的data数据
save to file,然后再处理,理论上是可行的,但是由于服务器有误,获取的数据不对,所以我怎么都解压不成功!!!!
示例如下:

Objective-C class used to zip / unzip compressed zip file. 
Usage: Add all the files to you project, and and framework libz.1.2.3.dylib. 

include ZipArchive.h 
using #import "ZipArchive/ZipArchive.h" * 
create zip file 

ZipArchive* zipFile = [[ZipArchive alloc] init];
[zipFile CreateZipFile2:@"zipfilename"]; 

// A OR [[zipFile CreateZipFile2:@"zipfilename" Password:@"your password"];
// if password needed, //empty password will get same result as A 

[zipFile addFileToZip:@"fullpath of the file" newname:@"new name of the file without path"];
//  ....add any number of files here 
[zipFile CloseZipFile2];
[zipFile release];

// remember to release the object * unzip compressed file 
ZipArchive* zipFile = [[ZipArchive alloc] init];
[zipFile UnzipOpenFile:@"zip file name"]; 

// B (the zip got no password) OR [zipFile UnzipOpenFile:@"zip file name" Password:@"password" ]; 
[zipFile UnzipFileTo:@"output path" overwrite:YES];
[zipFile UnzipCloseFile];
[zipFile release];

免责声明:文章转载自《iOS与服务器端 GZip压缩问题》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇【Python3爬虫】一次应对JS反调试的记录Map/HashMap 获取Key值的方法下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

centos7 tar.gz zip 解压命令

centos7 tar.gz zip 解压命令 tar负责打包,gzip负责压缩 tar-c: 建立压缩档案-x:解压-t:查看内容-r:向压缩归档文件末尾追加文件-u:更新原压缩包中的文件 这五个是独立的命令,压缩解压都要用到其中一个,可以和别的命令连用但只能用其中一个。下面的参数是根据需要在压缩或解压档案时可选的。 -z:有gzip属性的-j:有bz...

[Linux] Nginx响应压缩gzip

压缩和解压缩 1.本节介绍如何配置响应的压缩或解压缩以及发送压缩文件。 gzip on; 2.NGINX仅使用MIME类型text / html压缩响应 gzip_types text/plain application/xml;//指定压缩媒体类型 3.指定响应压缩的最小长度 gzip_min_length 1000; 4....

Nginx 笔记与总结(13)Nginx 的 gzip 压缩

使用 FireFox(40.0)访问博客园(http://www.cnblogs.com/),观察 http 头信息 请求头信息: Accept-Encoding gzip, deflate 表示浏览器接受的压缩方式有 gzip 和 deflate 响应头信息: Content-Encoding gzip 表示服务器返回内容的压缩方式是 gzip 注意...

nginx缓存静态资源,只需几个配置提升10倍页面加载速度

nginx缓存静态资源,只需几个配置提升10倍页面加载速度 首先我们看图说话 这是在没有缓存的情况下,这个页面发送了很多静态资源的请求: 1.png 可以看到,静态资源占用了整个页面加载用时的90%以上,而且这个静态资源还是已经在我使用了nginx配置压缩以后的大小,如果没有对这些静态资源压缩的话,那么静态资源加载应该会占用这个页面展示99%以上的时...

gzip压缩输出

一、gzip介绍         gzip是GNU zip的缩写,它是一个GNU自由软件的文件压缩程序,也经常用来表示gzip这种文件格式。软件的作者是Jean-loup Gailly和Mark Adler。1992年10月31日第一次公开发布,版本号是0.1,目前的稳定版本是1.2.4。         Gzip主要用于Unix系统的文件压缩。我们在Li...

Linux下的压缩和解压缩命令gzip/gunzip

作者:邓聪聪 Linux下的压缩和解压缩命令——gzip/gunzip yum -y install zip gzip (--安装压缩工具) gzip命令 gzip命令用来压缩文件。gzip是个使用广泛的压缩程序,文件经它压缩过后,其名称后面会多处“.gz”扩展名。 gzip是在Linux系统中经常使用的一个对文件进行压缩和解压缩的命令,既方便又...