ASIHTTPRequest 是一款非常有用的 HTTP 訪問開源項目,ASIHTTPRequest使用起來非常方便,可以有效減少代碼量.他的功能非常強大,可以實現異步請求,隊列請求,緩存,斷點續傳,進度跟蹤,上傳文件,HTTP 認證。同時它也加入了 Objective-C 閉包 Block 的支持.其官方網站: http://allseeing-i.com/ASIHTTPRequest/ 。
在使用ASI之前,需要導入一下框架:
CFNetWork.framework
SystemConfiguration.framework
MobileCoreServices.framework
libz.dylib
因為ASI是不支持ARC的,所以如果打算使用ARC功能,也就是arc和非arc混編,需要給非 ARC 模式的代碼文件加入 -fno-objc-arc 標簽。
一:ASIHTTPRequest實現上傳文件功能
//上傳- (IBAction)UpLoad:(UIButton *)sender { NSURL *url=[NSURL URLWithString:@"http://localhost:8080/UploadServer/UploadServlet"]; ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url]; [request setRequestMethod:@"POST"]; //方法一:主要應用與小文件,將小文件轉換為Data類型,再將Data類型的數據放入post請求體中上傳 NSData *dataImage=UIImageJPEGRepresentation([UIImage imageNamed:@"1.jpg"], 1); [request appendPostData:dataImage]; //方法二:直接從文件路徑找到文件,并放入post請求體中上傳,同樣適用與小文件 [request appendPostDataFromFile:[[NSBundle mainBundle]pathForResource:@"1" ofType:@"jpg"]]; //方法三:數據流方法(文件不分大小) //允許是從磁盤上讀取數據,并將數據上傳,默認為NO [request setShouldStreamPostDataFromDisk:YES]; [request setPostBodyFilePath:[[NSBundle mainBundle]pathForResource:@"1" ofType:@"jpg"]]; //使用異步請求 [request startAsynchronous];}
一:ASIHTTPRequest實現文件斷點下載
//下載- (IBAction)downLoad:(UIButton *)sender { //判斷請求是否為空.(如果雙擊開始,會產生一個不再受控制的請求) if (_request!=nil) { return; } //如果文件下載完畢就不再下載 if ([[NSFileManager defaultManager]fileExistsAtPath:[self getFilePath]]) { return; } NSString *string=@"http://localhost:8080/downloadSrver/xcode_6.dmg.dmg"; string=[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url=[NSURL URLWithString:string]; //創建ASIHTTPRequest請求 _request=[ASIHTTPRequest requestWithURL:url]; //設置文件存放的目標路徑 [_request setDownloadDestinationPath:[self getFilePath]]; [_request setDownloadProgressDelegate:self]; //允許斷點續傳,必須設置 [_request setAllowResumeForFileDownloads:YES]; //設置大文件下載的臨時路徑 //下載過程中文件一直保存在臨時文件中,當文件下載完成后才移入目標路徑下 [_request setTemporaryFileDownloadPath:[self getTemoPath]]; //設置代理 _request.delegate=self; _request.downloadProgressDelegate=self; //異步請求 [_request startAsynchronous];}- (IBAction)pause:(UIButton *)sender { //取消請求并清除代理 [_request clearDelegatesAndCancel]; _request=nil;}-(NSString *)getTemoPath{ //設置文件下載的臨時路徑 NSString *string=[NSTemporaryDirectory() stringByAppendingPathComponent:@"temp"]; return string;}//獲取沙盒-(NSString *)getFilePath{ NSString *document=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *filePath=[document stringByAppendingPathComponent:@"xcode6.dmg"]; return filePath;}//獲取下載進度-(void)setProgress:(float)newProgress{ _progressVIew.progress=newProgress; _label.text=[NSString stringWithFormat:@"%.2f%%",newProgress*100];}//因為ASI是非ARC,所以系統不會自動釋放,需要手動操作-(void)dealloc{ [_request clearDelegatesAndCancel];}
新聞熱點
疑難解答