0

在 iOS 中,我正在构建一个 http 请求,如下所示:

NSURL* url = [ NSURL URLWithString:[ NSString stringWithFormat: @"%@%@", [ HPSWebService getBaseURL ], @"Sync/PushObject"] ];

        // 'request' is defined within the base class and is set here to the class-specific server url
        request = [[NSMutableURLRequest alloc] initWithURL:url];

        NSString* jsonRequest = [NSString stringWithFormat: @"{\"collection\":\"responses\",\"id\":\"%@\",\"objectjson\":%@}",response.id,response.json];

        NSLog(@"HPSPushResponsesWebService jsonRequest = %@",jsonRequest);

        NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];

        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:self.contentEncoding forHTTPHeaderField:@"Content-Type"];
        [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody: requestData];

NSLog 输出如下:

2012-10-23 15:45:51.543 HPS[12523:707] HPSPushResponsesWebService jsonRequest = {"collection":"responses","id":"ZBZiaa43QciMSlMCp0Vtyw==","objectjson":{"_id":"{ \ "$binary\" : \"ZBZiaa43QciMSlMCp0Vtyw==\", \"$type\" : \"03\" }","_user":"Eddie Freshman","_lastmodifieddatelocalutc":"2012-10-23 14: 45:39","Fav Car":["Other:Me√´zoom"],"_formid":"{ \"$binary\" : \"OCDI9VNGStmN8GbOLSevtA==\", \"$type\" : \ "03\" }","是否需要跟进?":[],"_contactid":"{ \"$binary\" : \"+3144XhxQzCNzWKfqXCHyg==\", \"$type\" : \"03 \" }"}}

在 JSON 数据包含特殊字符(例如变音符号)之前,一切正常。发生这种情况时,内容长度实际上比应有的少 1 个字符。在示例中,umlat (e) 字符已转换为 √´(靠近 Fav Car 字符串)

我应该如何编码,以便在 http 请求中正确设置内容长度?

谢谢

4

0 回答 0