首页 文章

如何使用gziped内容发送HTTP POST请求?

提问于
浏览
10

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

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

2 回答

  • 19

    包括一个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];
    
  • -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];
    

相关问题