2012-05-02 13 views
9

私はiPhoneアプリを開発しており、手動でPOSTリクエストを作成しています。現在、JSONデータを送信する前に圧縮する必要があるため、サーバーにコンテンツを圧縮する方法を探しています。サーバーがJSONデータを必要とするため、コンテンツタイプヘッダーをgzipに設定することは受け入れられない可能性があります。透明なソリューションを探しています.JSONデータがgzipに圧縮されていることを伝えるヘッダを追加するだけのものです。gzipedコンテンツでHTTP POSTリクエストを送信するには?

私が知っている標準的な方法は、クライアントがエンコードを受け入れることをサーバーに伝えることですが、まず受け入れエンコードヘッダーで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

は、たとえばNSData+GZipため、OBJの-C 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]; 
関連する問題