在上篇文章中我谈到了使用 ASIHTTPRequest JSONKit 等开源库进行 POST JSON 到服务器的操做。IOS 使用 POST、GET 提交 JSON 数据到服务器因为在后续的开发中发现了一些问题(Stack overflow)Use ASIHTTPRequest to startAsynchronous and update UITableView but failed with EXC_BAD_ACCESS通过外国友人提示:ASIHTTPRequest 已经中止维护、在 IOS 7中存在已知 bug 。同时@未解 同窗也建议我采用 AFNetworking。可是又不想学习其它的库操做,因而尝试使用系统自带的库进行 POST 操做。json
(void)PostJson{ __block NSMutableDictionary *resultsDictionary; /* * 这里 __block 修饰符必需要 由于这个变量要放在 block 中使用 */ NSDictionary *userDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"first title", @"title",@"1",@"blog_id", nil];//假设要上传的 JSON 数据结构为 {"title":"first title","blog_id":"1"} if ([NSJSONSerialization isValidJSONObject:userDictionary])//判断是否有效 { NSError* error; NSData* jsonData = [NSJSONSerialization dataWithJSONObject:userDictionary options:NSJSONWritingPrettyPrinted error: &error];//利用系统自带 JSON 工具封装 JSON 数据 NSURL* url = [NSURL URLWithString:@"www.google.com"]; NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; [request setHTTPMethod:@"POST"];//设置为 POST [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setValue:[NSString stringWithFormat:@"%d",[jsonData length]] forHTTPHeaderField:@"Content-length"]; [request setHTTPBody:jsonData];//把刚才封装的 JSON 数据塞进去 __block NSError *error1 = [[NSError alloc] init]; /* *发起异步访问网络操做 并用 block 操做回调函数 */ [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse* response,NSData* data,NSError* error) { if ([data length]>0 && error == nil) { resultsDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1]; NSLog(@"resultsDictionary is %@",resultsDictionary); }else if ([data length]==0 && error ==nil){ NSLog(@" 下载 data 为空"); } else if( error!=nil){ NSLog(@" error is %@",error); } }]; } } }
事实上,我把这三行注释掉也是能够的,不知道为何,请知道去掉会有什么影响的朋友告知我。segmentfault
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setValue:[NSString stringWithFormat:@"%d",[jsonData length]] forHTTPHeaderField:@"Content-length"];