2012-05-02 77 views
9

我正在開發iPhone應用程序並手動構建POST請求。目前,在發送它之前需要壓縮JSON數據,因此尋找如何告訴服務器內容被壓縮。將內容類型標題設置爲gzip可能不可接受,因爲服務器需要JSON數據。我正在尋找透明的解決方案,就像添加一些頭,告訴JSON數據被壓縮成gzip。如何使用gziped內容發送HTTP POST請求?

我知道,標準的方法是告訴服務器客戶端接受編碼,但您需要首先使用accept編碼頭進行GET請求。就我而言,我想發佈已編碼的數據。

+0

發現:http://serverfault.com/questions/56700/is-it-possible-to-enable-http-compression-for-requests – Centurion

回答

-1

實踐一些通用的方法如下所示並設置合適的標題可能會對您有所幫助。

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

嗯,我看不出有任何編碼相關的報頭。我剛剛搜索了一下,你需要設置「Content-Encoding:gzip」標題 – Centurion

+0

這裏沒有關於gzipping的內容...... –

16

包括一個對象 - 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];