您的位置:首页 > 理论基础 > 计算机网络

网络请求判断连接和状态码

2016-05-27 13:52 344 查看
    NSURL *url = [NSURL
URLWithString:@"http://news.coolban.com";

   [NSURLConnection
sendAsynchronousRequest:request
queue:[NSOperationQueue
mainQueue]
completionHandler:^(NSURLResponse *
_Nullable response,
NSData *
_Nullable data,
NSError *
_Nullable connectionError) {

        

        //连接错误

        if(connectionError){

            errorBlock();

//            NSLog(@"%@",connectionError);

            return;

        }

        

        //得到状态码

        //判断状态码是200或者304就是成功

        NSHTTPURLResponse *httpResponse =  (NSHTTPURLResponse *)response;

        if(httpResponse.statusCode ==
200 || httpResponse.statusCode ==
304){

            //访问成功

            //json反序列化

            id result =  [NSJSONSerialization
JSONObjectWithData:data
options:0 error:NULL];

            

            NSMutableArray *mArray = [NSMutableArray
array];

            //遍历array

            [result enumerateObjectsUsingBlock:^(id 
_Nonnull obj, NSUInteger idx,
BOOL * _Nonnull stop) {

                CZNews *news = [CZNews
newsWithDictionary:obj];

                [mArray addObject:news];

            }];

            

            sucessBlock(mArray.copy);

            

        }else{

            errorBlock();

//            NSLog(@"服务器错误");

        }

        

    }];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: