AFNetworking 使用 核心代码
///////////////////////////以前用法/////////////////////////////////////////////////////////////
//使用AFHTTPRequestOperation 创建HTTP请求 --- GET请求
//1,url
NSString *URLTmp = @"http://api.budejie.com/api/api_open.php?a=list&appname=baisibudejie&asid=F20FB3C5-A3A6-4ACA-9B22-44FB308FCB23&c=data&client=iphone&device=ios%20%E8%AE%BE%E5%A4%87&from=ios&jbk=1&mac=02%3A00%3A00%3A00%3A00%3A00&market=&openudid=6bcaf1e795d8e4cf82ce78caa1fc33b9a7c671d5&page=0&per=20&type=10&udid=&ver=2.9.3";
URLTmp = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //转码成UTF-8 否则可能会出现错误
//2,请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
//3,创建HTTP请求
AFHTTPRequestOperation *afOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//4,
afOperation.responseSerializer = [AFJSONResponseSerializer serializer];
//5,开始请求
[afOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//将字符串 编码后 转成 NSData
NSData *resData = [[NSData alloc] initWithData:[operation.responseString dataUsingEncoding:NSUTF8StringEncoding]];
//系统自带JSON解析
NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@",resultDic);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure: %@", error);
}];
//6,
[[NSOperationQueue mainQueue] addOperation:afOperation];
//------批量处理
// NSMutableArray *mutableOperations = [NSMutableArray array];
// for (NSURL *fileURL in filesToUpload) {
// NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];
// }];
//
// AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//
// [mutableOperations addObject:operation];
// }
//
// NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
// NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
// } completionBlock:^(NSArray *operations) {
// NSLog(@"All operations in batch complete");
// }];
// [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
//
///////////////////////////新用法/////////////////////////////////////////////////////////////
//提交GET ,
//1,创建AFHTTPRequestOperationManager HTTP请求操作管理对象
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//2,发送GET请求(默认解析JSON,plist. )
[manager GET:URLTmp
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// NSLog(@"JSON: %@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
// POST 单个请求
//1,创建AFHTTPRequestOperationManager HTTP请求操作管理对象
AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
//2,发送POST请求(默认解析JSON,plist. )
NSDictionary *parameters = @{ };//空参数
[manager1 GET:URLTmp
parameters:parameters //参数
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// NSLog(@" POST JSON: %@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
//POST 多个请求
AFHTTPRequestOperationManager *manager2 = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters2 = @{};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager2 POST:@"http://example.com/resources.json"
parameters:parameters2
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:@"image" error:nil];
}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// NSLog(@"Success: %@", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//NSLog(@"Error: %@", error);
}];
//
////////////////////////////////////////////////////////////////////////////////////////
//创建一个下载文件的任务
//AFURLSessionManager创建并完善了一个NSURLSession的对象基于遵从NSURLSessionDelegate与NSURLSessionDataDelegate协议 NSURLSessionConfigration对象
//1,1 创建配置对象 (上传 下载 使用 , 配置超时值,缓存策略,连接要求,和其他类型的信息,)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//1.2 通过配置对象,创建AFURLSessionManager 管理对象
AFURLSessionManager *managerDown = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
//2,请求对象
NSURL *URL = [NSURL URLWithString:@"http://img4.mypsd.com.cn/20110707/Mypsd_59710_201107071333160001B.jpg"];
NSURLRequest *requestDown = [NSURLRequest requestWithURL:URL];
//3,创建下载任务
NSURLSessionDownloadTask *downloadTask = [managerDown downloadTaskWithRequest:requestDown
progress:nil
destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
// 3,1 返回 一个下载到的路径
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; //文件路径
}
completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//此处已经回到主线程 (处理UI)
// NSLog(@"File downloaded to: %@", filePath);
}];
//4, 开始
[downloadTask resume];
////////////////////////////////////////////////////////////////////////////////////////
//创建一个上传文件的任务
//AFURLSessionManager创建并完善了一个NSURLSession的对象基于遵从NSURLSessionDelegate与NSURLSessionDataDelegate协议 NSURLSessionConfigration对象
//1,1 创建配置对象 (上传 下载 使用 , 配置超时值,缓存策略,连接要求,和其他类型的信息,)
NSURLSessionConfiguration *configuration1 = [NSURLSessionConfiguration defaultSessionConfiguration];
//1.2 通过配置对象,创建AFURLSessionManager 管理对象
AFURLSessionManager *managerUp = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration1];
//2,请求对象
NSURL *upURL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *requestUp = [NSURLRequest requestWithURL:upURL];
//3,创建上传任务
NSURLSessionUploadTask *uploadTask = [managerUp uploadTaskWithRequest:requestUp
fromFile:[NSURL fileURLWithPath:@"file://path/to/image.png"]//上传文件的URL
progress:nil
completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
// NSLog(@"Error: %@", error);
} else {
// NSLog(@"Success: %@ %@", response, responseObject);
}
}];
//4,开始
[uploadTask resume];