【问题标题】:How to send HTTP POST request with gziped content?如何发送带有压缩内容的 HTTP POST 请求?
【发布时间】:2012-05-11 17:54:36
【问题描述】:

我正在开发 iPhone 应用程序并手动构建 POST 请求。目前,需要在发送之前压缩 JSON 数据,所以看看如何告诉服务器内容被压缩。将内容类型标头设置为 gzip 可能是不可接受的,因为服务器需要 JSON 数据。我正在寻找透明的解决方案,比如添加一些标头,告诉 JSON 数据被压缩到 gzip 中。

我知道,标准的方法是告诉服务器客户端接受编码,但你需要先用接受编码头发出 GET 请求。就我而言,我想发布已经编码的数据。

【问题讨论】:

标签: iphone objective-c http gzip http-post


【解决方案1】:

实现一些通用方法,例如以下并设置适当的 Header 可能会对您有所帮助。

// 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];

【讨论】:

  • 嗯,我没有看到任何与编码相关的标头。我刚刚google了一下,你需要设置“Content-Encoding: gzip” header
【解决方案2】:

包含一个 Obj-C gzip 包装器,例如 NSData+GZip,并使用它来编码您的 NSURLRequest 的正文。还记得相应地设置Content-Encoding,这样网络服务器就会知道如何处理您的请求。

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];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    • 2016-02-01
    • 1970-01-01
    相关资源
    最近更新 更多