0

我已经搜索过,但在这里找不到这个:

我正在尝试将 NSData 对象发送到 Web 服务。NSData 对象是一个使用 iOS 5 内置 JSON 的 JSON 对象。

我需要进行异步发送,然后检查服务器返回的响应。

我不想使用任何 3rd 方库。

这是我已经拥有但不起作用的东西:

NSDictionary * initialLogAsJSON = [NSDictionary dictionaryWithObjects:items forKeys:keys];

NSError * error;

NSData * jsonData = [NSJSONSerialization dataWithJSONObject:initialLogAsJSON options:NSJSONWritingPrettyPrinted error:&error];

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:kURLSendTestStartedDataToTenOneServer ]];

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

[NSURLConnection sendAsynchronousRequest:request
                                   queue:self.queue
                       completionHandler:^( NSURLResponse * response, NSData * data, NSError * error )
                                        {
                                            NSLog( @"If finished with reponse = %@\nData: %@\nError %@", response, data, error );
                                            // do something useful
                                        }
];
4

2 回答 2

2

两个问题:

1)您应该断言或记录该调用中的每个对象,这样您就知道没有什么是零。

2)你有一个错字:

[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"appliction/json" forHTTPHeaderField:@"Content-Type"];

第二个应用程序缺少“a”

于 2012-08-17T23:28:34.227 回答
1

实际上问题比..

归结为 URL 为零 - 因为源字符串中有一些有趣的转义字符。

这是我的最终(工作)实现:

NSDictionary * mainJSON = [NSDictionary dictionaryWithObjects:mainItems forKeys:mainKeys];

NSError * error;

NSData * jsonData = [NSJSONSerialization dataWithJSONObject:mainJSON options:NSJSONWritingPrettyPrinted error:&error];

NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];

NSString * serverString = [NSString stringWithFormat:@"%@", kURLServer];

NSString * urlString = [NSString stringWithFormat:@"%@%@", serverString, jsonString];

NSString * webStringURL = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL * url = [NSURL URLWithString:webStringURL];

NSAssert( url != nil, @"URL nil - Check string values for URL to Server!" );

dispatch_async( kBackgroundQueue, ^
                                   {
                                       NSData * data = [NSData dataWithContentsOfURL:url];
                                                   [self performSelectorOnMainThread:@selector( receivedResponseFromServer: )
                                                                          withObject:data
                                                                       waitUntilDone:YES];
                                   }
               );
于 2012-08-17T23:38:40.433 回答