我正在开发 iPhone 应用程序,手动构建 POST 请求。目前,需要在发送数据之前压缩 JSON 数据,因此正在寻找如何告诉服务器内容已经压缩。将内容类型标头设置为 gzip 可能不可接受,因为服务器期望 JSON 数据。我正在寻找透明的解决方案,例如只需添加一些标头即可告知 JSON 数据已压缩为 gzip。
我知道,标准方法是告诉服务器客户端接受编码,但您需要先使用接受编码标头进行 GET 请求。在我的情况下,我希望发布已经编码的数据。
我正在开发 iPhone 应用程序,手动构建 POST 请求。目前,需要在发送数据之前压缩 JSON 数据,因此正在寻找如何告诉服务器内容已经压缩。将内容类型标头设置为 gzip 可能不可接受,因为服务器期望 JSON 数据。我正在寻找透明的解决方案,例如只需添加一些标头即可告知 JSON 数据已压缩为 gzip。
我知道,标准方法是告诉服务器客户端接受编码,但您需要先使用接受编码标头进行 GET 请求。在我的情况下,我希望发布已经编码的数据。
包含一个Obj-C的gzip包装器,例如NSData+GZip
,并使用它来编码你的NSURLRequest
的主体。同时记得设置Content-Encoding
,以便Web服务器知道如何处理你的请求。
NSData *requestBodyData = [yourData gzippedData];
NSString *postLength = [NSString stringWithFormat:@"%d", requestBodyData.length];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
[request setHTTPBody:requestBodyData];
实现一些通用的方法,例如以下内容,并设置适当的头部可能会对您有所帮助。
// constructing connection request for url with no local and remote cache data and timeout seconds
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:callingWebAddress]];// cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:timoutseconds];
[request setHTTPMethod:@"POST"];
NSMutableDictionary *headerDictionary = [NSMutableDictionary dictionary];
[headerDictionary setObject:@"application/json, text/javascript" forKey:@"Accept"];
[headerDictionary setObject:@"application/json" forKey:@"Content-Type"];
//Edit as @centurion suggested
[headerDictionary setObject:@"Content-Encoding" forKey:@"gzip"];
[headerDictionary setObject:[NSString stringWithFormat:@"POST /Json/%@ HTTP/1.1",method] forKey:@"Request"];
[request setAllHTTPHeaderFields:headerDictionary];
// allocation mem for body data
self.bodyData = [NSMutableData data];
[self appendPostString:[parameter JSONFragment]];
// set post body to request
[request setHTTPBody:bodyData];
NSLog(@"sending data %@",[[[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding]autorelease]);
// create new connection for the request
// schedule this connection to respond to the current run loop with common loop mode.
NSURLConnection *aConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//[aConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
self.requestConnenction = aConnection;
[aConnection release];