在Web服务中传递数组
在Web服务中传递数组
我正在开发一个应用程序,在其中我使用WebServices将我的联系人号码发送到服务器。我会得到一个联系人号码的数组,并通过WebServices发送联系人数组。以下是代码:
NSString *myRequestString1 = [[NSString alloc] initWithFormat:@"contact_numbers=%@",MobiileArray ];
NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString1 UTF8String ] length: [ myRequestString1 length ] ];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:@"http://myproject.in/myproject-contacts.php"]];
[request setHTTPMethod: @"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody: myRequestData];
NSURLResponse *response;
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err];
NSError* error;
NSMutableArray* result = [NSJSONSerialization JSONObjectWithData:returnData
options:kNilOptions
error:&error];
NSLog(@"result: %@", result);
但是响应为空,我的代码有什么错误吗?你能给我一些建议吗?谢谢。
问题的出现的原因是在使用Webservices传递数组时,代码中的一些部分错误。解决方法是使用正确的代码来传递数组。
原始代码如下:
NSString *myRequestString1 = [[NSString alloc] initWithFormat:@"contact_numbers=%@",MobiileArray ]; NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString1 UTF8String ] length: [ myRequestString1 length ] ];
修改后的代码如下:
NSDictionary *dict = [NSDictionary dictionaryWithObject: MobiileArray forKey:@"contact_numbers"]; NSString* myRequestString1 = [MobiileArray JSONRepresentation]; NSData *myRequestData = [myRequestString1 dataUsingEncoding:NSUTF8StringEncoding];
还需要添加以下代码:
[request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
问题解决后,原始代码中的参数`contact_numbers`被正确地传递给了Webservices。
该问题的解决方法可以在以下链接中找到更多信息:[stackoverflow.com/questions/9968042](http://stackoverflow.com/questions/9968042)