iOS REST Web Service(2)AFNetworking

本文深入讲解iOS中GET和POST请求的实现方式,演示如何使用AFNetworking框架进行数据上传和下载,包括请求创建、任务管理及进度监控。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GET请求
// An highlighted block
-(void)startRequest{
	//设置请求地址
	NSString *strURL=[[NSString alloc] initWithFormat:@"http://www.a.com?id=%@&type=%@",@"1",@"jsonType"];
	strURL=[strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSetQueryAllowedCharacterSet]];
	NSURL *url=[NSURL URLWithString:strURL];
	//创建NSURLRequest对象
	NSURLRequest *request=[[NSURLRequest alloc] initWithURL:url];
	//创建默认的会话配置对象
	NSURLSessionConfiguration *defaultConfig=[NSURLSessionConfiguration defaultSessionConfiguration];
	//AFURLSessionManager对象,它是由AFNetworking框架提供,负责管理会话。
	AFURLSessionManager *manager=[[AFURLSessionManager alloc] initWithSessionConfiguration:defaultConfig];
	//通过AFURLSessionManager调用dataTaskWithRequest:completionHandler:方法,创建NSURLSessionDataTask数据任务。方法由AFURLSessionManager提供,第一个参数是NSURLRequest对象,第二个参数是任务回调的代码块。
	NSURLSessionDataTask *task=[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){
		NSLog(@"请求完成");
		if(!error){
			//任务成功结束时的回调语句responseObject是从服务器返回的json对象,它可以是字典或数组类型,AFURLSessionManager不需要我们自己解析JSOn字符串。
			[self reloadView:responseObject];
		}else{
			NSLog(@"error:%@",error.localizedDescription);
		}
	}];
	[task resume];
}
POST请求
// An highlighted block
-(void)startRequest{
	//设置请求地址
	NSString *strURL=:@"http://www.a.com";
	NSURL *url=[NSURL URLWithString:strURL];
	//设置参数
	NSString *post=[NSString stringWithFormat:@"id%d&type=%@",1,@"jsonType"];
	NSData *postData=[post dataUsingEncoding:NSUTF8StringEncoding];
	//创建NSMutableURLRequest对象
	NSMutableURLRequest*request=[NSMutableURLRequest requestWithURL:url];
	[request setHTTPMethod:@"POST"];
	[request setHTTPBody:postData];
	//创建默认的会话配置对象
	NSURLSessionConfiguration *defaultConfig=[NSURLSessionConfiguration defaultSessionConfiguration];
	//AFURLSessionManager对象,它是由AFNetworking框架提供,负责管理会话。
	AFURLSessionManager *manager=[[AFURLSessionManager alloc] initWithSessionConfiguration:defaultConfig];
	//通过AFURLSessionManager调用dataTaskWithRequest:completionHandler:方法,创建NSURLSessionDataTask数据任务。方法由AFURLSessionManager提供,第一个参数是NSURLRequest对象,第二个参数是任务回调的代码块。
	NSURLSessionDataTask *task=[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){
		NSLog(@"请求完成");
		if(!error){
			//任务成功结束时的回调语句responseObject是从服务器返回的json对象,它可以是字典或数组类型,AFURLSessionManager不需要我们自己解析JSOn字符串。
			[self reloadView:responseObject];
		}else{
			NSLog(@"error:%@",error.localizedDescription);
		}
	}];
	[task resume];
}
下载数据
// An highlighted block
#import "AFNetworking.h"
@interface ViewController()
@property(weak,nonatiomic) IBOutlet UIProgressView *progressView;
@property(weak,nonatiomic) IBOutlet UIImageView *imageView1;
@property(weak,nonatiomic) IBOutlet UIButton *button1;
@end

@imlementation ViewController
-(IBAction)onClick:(id)sender{
	NSString *strURL=[[NSString alloc] initWithFormat:@"http://www.a.com?fileName=%@",@"test1.jpg"];
	NSURL *url=[NSURL URLWithString:strURL];
	NSURLRequest *request=[NSURLRequest requestWithURL:url];
	NSURLSessionConfiguration *defaultConfig=[NSURLSessionConfiguration defaultSessionConfiguration];
	AFURLSessionMeanager *manager=[[AFURLSessionMeanager alloc]  initWithSessionConfiguration:defaultConfig];
	//通过AFURLSessionMeanager对象获得下载会话任务对象,request是请求对象;progress是参数代码块,用来获得当前运行进度,代码块的参数downloadProgress是NSProgress类型;destionation参数是下载文件的保存路径;response是应答对象;completionHandler参数是代码亏,是从服务器返回应答数据时回调的。
	NSURLSessionDownloadTask *downloadTask=[manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){
		//获得下载进度对象downloadProgress的本地化信息。
		NSLog([downloadProgress localizedDescription]);
		dispatch_async(dispatch_get_main_queue(),^{
			//更新下载进度
			[self.progressView setProgress:downloadProgress.fractionCompleted animated:TRUE];
		});
		//保存下载文件的代码块
		}destination:^NSURL *(NSURL*targetPath,NSURLResporse *response){
			NSString*downloadsDir=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,TRUE) objectAtIndex:0];
			//获得应用沙箱目录下推荐的文件名,suggestedFilename是获得推荐的文件名,这个文件名就是服务器端存储的文件名。
			NSString *downloadStrPath=[downloadsDir stringByAppendingPathComporent:[response suggestedFilename]];
			NSURL *downloadURLPath=[NSURL fileURLWithPath:downloadStrPath];
			return downloadURLPath;
		//从服务器返回应答数据时回调的代码块,这里设置图片,显式下载的图片。
		}completionHandler:^(NSURLResponse *response,NSURL*filePath,NSError *error){
			NSLog(@"file downloaded to:%@",filePath);
			NSData *imgData=[[NSData alloc] initWithContentOfURL:filePath];
			UIImage*img=[UIImage imageWithData:imgData];
			self.imageVeiw1.image=img;
	}];
	[downloadTask resume];
}
@end
上传数据
// An highlighted block
#import "AFNetworking.h"
@interface ViewController()
@property(weak,nonatiomic) IBOutlet UIProgressView *progressView;
@property(weak,nonatiomic) IBOutlet UIImageView *imageView1;
@property(weak,nonatiomic) IBOutlet UIButton *button1;
@end

@imlementation ViewController
-(IBAction)onClick:(id)sender{
	NSString *uploadStrURL=@"http://www.a.com";
	NSDictionary *params=@{@"id":@"1"};
	NSString *filePath=[[NSBundle mainBundle] pathForResource:@"test2" ofType:@"jpg"];
	//创建NSMutableURLRequest对象,它通过AFHTTPRequestSerializer对象的multipartFormRequestWithMethod实现,其中AFNTTPRequestSerializer是HTTP请求序列化对象,封装了HTTP请求参数。该方法可以发送multipart/form-data格式的表单数据;method参数的请求方法一般是POST和PUT;URLString参数是上传时服务器的地址;parameters是请求参数,他是字典结构;constructingBodyWithBlock是请求体代码块;error是错误对象。
	NSMutableURLRequest *request=[[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:uploadStrURL parameters:params constructingBodyWithBlock:^(id <AFMultipartFormData>{
		//调用AFMultipartFormData的appendPartWithFileURL:name:error:方法,添加multipart/form-data格式的表单数据。这种格式的数据被分割成小段进行上传,该方法的第一个参数是要上传的文件路径;第二个参数name是与数据相关的名称,一般是file,相当于HTML中表单内的选择文件空间<input type="file">类型;第三个参数fileName是文件名,是放在请求头中的文件名,不能为空,可以与本地文件名不同;第四个参数mimeType是数据相关的MIME类型;最后一个参数error是错误对象。
		[formData appendPartWithFileURL:[NSURLfileURLWithPath:filePath] name:@"file" fileName:@"1.jpg" mimeType:@"image/jpeg" error:nil];
	} error:nil)];
	AFURLSessionMeanager *manager=[[AFURLSessionMeanager alloc]  initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
	//创建上传会话任务,方法中request参数是请求对象;progress参数是代码块用来获得当前运行的进度,代码块的参数uploadProgress是NSProgress类型;completionHandler代码块,如果error为nil,则上传成功。
	NSURLSessionUploadTask *uploadTask=[manager uploadTaskWithStreamedRequest:request progress:^(NSProgress *uploadProgress){
		//获得上传进度对象uploadProgress的本地化信息。
		NSLog([uploadProgress localizedDescription]);
		dispatch_async(dispatch_get_main_queue(),^{
			//更新上传进度
			[self.progressView uploadProgress.fractionCompleted animated:TRUE];
		});
		//从服务器返回应答数据时回调的代码块,这里设置图片,显式下载的图片。
		}completionHandler:^(NSURLResponse *response,id esponseObject,NSError *error){
			if(!error){
				NSLog(@"上传成功");
			}
			else
			{
				NSLog(@"上传失败:%@",error.localizedDescription);
			}
			NSData *imgData=[[NSData alloc] initWithContentOfURL:filePath];
			UIImage*img=[UIImage imageWithData:imgData];
			self.imageVeiw1.image=img;
	}];
	[downloadTask resume];
}
@end

参考资料
《IOS开发指南 从HELLO WORLD到APP STORE上架 第5版》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值