iOS 原生网络请求

原生 网络请求

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=ios"] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:120];

//创建会话
    NSURLSession *session = [NSURLSession sharedSession];



    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        

        if (error == nil) {

            /*

             NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

             NSLog(@"data: %@", dataStr);

             */

            

            //json --> data

            //NSJSONSerialization *jsonData = [NSJSONSerialization dataWithJSONObject:<#(id)#> options:<#(NSJSONWritingOptions)#> error:<#(NSError *__autoreleasing *)#>]

            /*

             options:

             1.读取reading

             NSJSONReadingMutableContainers 生成可变的对象,不设置这个option,默认是创建不可变对象

             NSJSONReadingMutableLeaves 生成可变的字符串MutableString(iOS7+有bug)

             NSJSONReadingAllowFragments 允许json数据最外层不是字典或者数组

             2.写入writing

             NSJSONWritingPrettyPrinted 生成json数据是格式化的,有换行,可读性高

             */

            //data --> json

            

            NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

            NSLog(@"data: %@", dataStr);

        }

    }];

    

    [task resume];

你可能感兴趣的:(iOS 原生网络请求)