简单的从服务器获取数据以及反序列化

来源:互联网 发布:qt5 socket编程 编辑:程序博客网 时间:2024/05/16 23:36

范例(从本地服务器获取数据打印出来):

//确定urlNSURL *url = [NSURL URLWithString:@"http://127.0.0.1/demo.json"];//建立请求(参数:资源路径、缓存策略、超时期限,默认60s)NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15 ];//建立connection,发送请求到服务器[NSURLConnection sendAsynchoronousRequest:request queue:    [[NSOperationQueue alloc] init] completionHandler:        ^(NSURLResponse *response, NSData *data, NSError *connectionError){    if(connectionError || data == nil)    {        NSLog(@"网络出错,稍后再试");        return;    }    //把数据显示出来    NSLog[@"%@", [[NSString alloc]         initWithData:data encoding:NSUTF8StringEncoding]);    //JSON解析数据(JSON的反序列化)    id result1 = [NSJSONSerialization JSONObjectWithData:data         options:NSJSONReadingMutableContainers error:NULL];    //JSONKit解析    id result2 = [[JSONDecoder decoder] objectWithData:data];    //Plist的反序列化    id result3 = [NSPropertyListSerialization propertyListWithData:data        options:0 format:NULL error:NULL];    NSLog(@"result = %@", result);}];注意:url中不能有中文或者空格之类的特殊符号,为了以防万一,最好用百分号转义urlString = [rulString stringByAddingPercengtEscapesUsingEncoding:NSUTF8StringEncoding];
0 0