1

我有这个方法-

NSArray *objects = [NSArray arrayWithObjects:appDelegate.UserID,itemName.text,@"1",@"1",itemDegem.text,itemDescription.text, nil];
NSArray *keys = [NSArray arrayWithObjects:@"userId",@"itemName",@"itemCategoryId",@"regionId",@"degemName",@"itemDescription", nil];

NSDictionary *registerDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *jsonRequest = [registerDict JSONRepresentation];    
NSLog(@"jsonRequest is %@", jsonRequest);

NSURL *url = [NSURL URLWithString:@"http://www.somedomain.com/method"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

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

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

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
    self.responseData = [NSMutableData data];
}

但是当我在我的对象中发送不是英语的字符串时,我从服务器收到错误。现在,我知道这是一个 UTF8 问题,但我确实将它设置为 UTF8。有人可以帮我弄清楚吗?

4

1 回答 1

4

我认为错误strlen([jsonRequest UTF8String])不等于[jsonRequest length].

用于使用NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];UTF8 编码将 NSString 转换为 NSData。

于 2012-05-07T20:36:08.293 回答