IOS 7 利用系统自带库进行 POST JSON 异步访问操作

发布时间:2019-06-13 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了IOS 7 利用系统自带库进行 POST JSON 异步访问操作脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

在上篇文章中我谈到了使用 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 操作。

(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);

        }
    }];
        }
    }
   }

事实上,我把这三行注释掉也是可以的,不知道为什么,请知道去掉会有什么影响的朋友告知我。

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

脚本宝典总结

以上是脚本宝典为你收集整理的IOS 7 利用系统自带库进行 POST JSON 异步访问操作全部内容,希望文章能够帮你解决IOS 7 利用系统自带库进行 POST JSON 异步访问操作所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。