AFNetworking形式-与-NSURLConnection形式的网络请求

一:NSURLConnection网络请求

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 异步方法
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", str);
}];

二:AFNetworking形式网络请求

  1.方法一

// 使用AFNetworking 2.0框架的网络请求
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.requestSerializer.timeoutInterval = 30; manager.responseSerializer = [AFJSONResponseSerializer serializer]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"]; // 很多后台格式问题用此行解决,不一定必须 // httpBody // NSDictionary *httpBodyParameters = @{@"http": @"body"};
// kJsonSourceURLAddress请求地址
[manager GET:kJsonSourceURLAddress_1 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSDictionary *jsonDict = (NSDictionary *)responseObject;
//        [self displayWithParsedDic:jsonDict];
        
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"错误" message:[NSString stringWithFormat:@"%@", error] delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil, nil];
        [alert show];
}];

  2.方法二

NSURL *url = [NSURL URLWithString:kJsonSourceURLAddress_1];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];

//    NSMutableURLRequest *test = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:kJsonSourceURLAddress_1 parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        // TODO 文件上传
////        [formData appendPartWithFileData:<#(NSData *)#> name:<#(NSString *)#> fileName:<#(NSString *)#> mimeType:<#(NSString *)#>]
//    }];

//    // 网络GET请求
//    NSMutableURLRequest *requestGet = [NSMutableURLRequest requestWithURL:url];
//    requestGet.HTTPMethod = @"GET";
//    requestGet.timeoutInterval = 30;
//
//    // 网络POST请求
//    NSMutableURLRequest *requestPost = [NSMutableURLRequest requestWithURL:url];
//    requestPost.HTTPMethod = @"POST";
//    requestPost.timeoutInterval = 30;
//    NSData *httpBody = [kJsonSourceURLAddress_1 dataUsingEncoding:NSUTF8StringEncoding];
//    NSLog(@"%@", httpBody);
//    requestPost.HTTPBody = httpBody;

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
                                         initWithRequest:urlRequest];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
// 很多后台格式问题用此行解决,不一定必须
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"%@", responseObject);
        NSDictionary *jsonDict = (NSDictionary *)responseObject;
        [self displayWithParsedDic:jsonDict];
        
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"错误" message:[NSString stringWithFormat:@"%@", error] delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil, nil];
        [alert show];
}];

// 上传进度
//    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
//
//    }];

[[NSOperationQueue mainQueue] addOperation:operation];

补充:系统自带的json解析

// json数据解析成NSDictionary
NSDictionary *parseData = [NSJSONSerialization JSONObjectWithData:_jsonData options:NSJSONReadingMutableLeaves error:&error];
// NSDictionary转换成json()
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。