iOS HttpRequest with umlaut has incorrect length

一个人想着一个人 提交于 2019-12-11 20:25:00

问题


Within iOS I am building an http request as follows:

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

The NSLog output is as follows:

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\" }","Follow-up Required?":[],"_contactid":"{ \"$binary\" : \"+3144XhxQzCNzWKfqXCHyg==\", \"$type\" : \"03\" }"}}

It all works fine until the JSON data contains a special character (such as an umlaut). When this happens then the content length is actually 1 char less than it should be. In the example the umlat (e) char has been converted into ë (near the Fav Car string)

How should I code this so the content length is correctly set within the http request?

Thanks

来源:https://stackoverflow.com/questions/13033197/ios-httprequest-with-umlaut-has-incorrect-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!