AFNetWorking之GET,POST,上传图片,下载文件进
1.GET
- (void)testgetDemo {
NSString *path = @"http://m.weather.com.cn/data/101010100.html";
//2.下载管理类对象
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//3.默认传输的数据类型
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//4.默认传输数据的样式
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//5执行下载
/*
第一个参数:请求数据的地址
第二个参数:附加信息(可以为空)
第三个参数:执行成功后的操作
第四个参数:执行失败后的操作
*/
[manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//第一个请求类,默认的参数
//第二个:请求获得数据
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
//解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error.description);
}];
}
2.POST
#pragma mark - post请求
- (void)testPost {
NSString *path = @"http://baidu.com";
//下载管理类
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//默认传输数据的类型
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//传输数据的样式
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//post请求
[manager POST:path parameters:@{@"user":@"fangbingbing",@"password":@"123456"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error.description);
}];
}
3.POST上传图片到服务器
#pragma mark - post上传头像
- (void)postImageToSever {
//获取地址
NSString *path = @"http://10.0.178.12/iOS_PHP/upload.php"; //下载管理类的对象 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; //默认传输的数据类型是二进制
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//第三个参数:进行上传数据的保存操作
[manager POST:path parameters:nil constructingBodyWithBlock:^(idformData) {
//找到要上传的图片
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"menu_bg_01-hd.jpg" ofType:nil];
/*
第一个参数:将要上传的数据的原始路径
第二个参数:要上传的路径的key
第三个参数:上传后文件的别名
第四个参数:原始图片的格式
*/
[formData appendPartWithFileURL:[NSURL fileURLWithPath:imagePath] name:@"file" fileName:@"2345.png" mimeType:@"image.jpg" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error.description);
}];
}
4.下载数据进度监测
#pragma mark - 下载数据
- (void)downLoadData {
_progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
_progressView.frame = CGRectMake(10, 100, 300, 10);
_progressView.backgroundColor = [UIColor redColor];
[self.view addSubview:_progressView];
//1.获取地址
NSString *path = @"http://imgcache.qq.com/club/item/avatar/zip/7/i87/all.zip";
//2.专门进行下载的管理类
AFURLSessionManager *sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; //默认传输的数据类型是二进制
sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
//模式是下载模式
NSProgress *downloadProgress = nil;
/* 第一个参数:将要下载文件的路径 第二个参数:下载进度 第三个参数:(block):处理下载后文件保存的操作 第四个参数(block):下载完成的操作 */
NSURLSessionDownloadTask *task = [sessionManager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]] progress:&downloadProgress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
//沙盒的Documents路径
NSString *downLoadPath = [NSString stringWithFormat:@"%@/Documents/downLoadData.zip",NSHomeDirectory()];
/** 区分:fileURLWithPath:与urlWithString: 前者用于网络(AFNetWorking),后者用于(NSURLConnection等系统的数据请求类) */
//返回下载后保存文件的路径
return [NSURL fileURLWithPath:downLoadPath];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { NSLog(@"filePah:%@",filePath); } ];
//开始下载 [task resume];
//利用kvo监听下载进度
//利用kvo 通过将当前类的对象设置成观察者(监听者),让当前类观察downloadProgress里面的fractionCompleted属性的变化
//NSKeyValueObservingOptionNew:标记值的变化,这个是新值 //NSKeyValueObservingOptionOld:旧值
[downloadProgress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}
#pragma mark - //kvo观察者触发的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context {
NSLog(@"keypath:%@,object:%@,change:%@",keyPath,object,change);
//获取 进度变化
float chanagefl = [[object valueForKeyPath:keyPath] floatValue];
//
_progressView.progress = chanagefl; //开始不能体现变化,是因为下载的过程是异步的,不能实时的获取值的变化.所以利用多线程的知识解决问题
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
_progressView.progress = chanagefl;
}];
}