iOS Development-HTTP Terminator "ASI"

Source: Internet
Author: User

Asi

Full name is ASIHTTPRequest, nickname "http Terminator", the function is very powerful
High operational efficiency based on the underlying cfnetwork framework
Unfortunately the author has already stopped updating, there are some potential bugs no one to solve
Many of the company's old projects are remnants of its shadow, many of the previous iOS projects are ASI + Sbjson
Is it possible to use ASI as one of the standards of testing for an established iOS programmer?

The GitHub address of ASI
Https://github.com/pokeb/asi-http-request

Use of ASI Reference
Http://www.cnblogs.com/dotey/archive/2011/05/10/2041966.html
http://www.oschina.net/question/54100_36184

Send a sync request
 #import "ASIHTTPRequest.h" //1. Create a requestNsurl*url = [Nsurlurlwithstring:@"Http://192.168.1.103:8080/Server/login?username=123&pwd=123"]; ASIHTTPRequest *request = [ASIHTTPRequest requestwithurl:url];request. Timeoutseconds=5;//Timeout//2. Send a sync request[Request startsynchronous];//3. Get the error messageNserror*error = [request ERROR];if(Error) {NSLog(@"Something went wrong.");}Else{//Get response from serverNSData *data = [request ResponseData];}//[request ResponseData]
Sending an asynchronous request
// 1.创建请求NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/MJServer/login?username=123&pwd=123"];ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];request.timeOutSeconds5// 超时// 2.设置代理request.delegateself;// 3.发送异步请求[request startAsynchronous];// ASI通过代理的方式处理异步请求,请求成功、失败都会通知代理//   代理需要遵守ASIHTTPRequestDelegate协议
Asihttprequestdelegate
//接收到服务器的数据就调用- (void**)data//请求失败就调用- (void*)request//请求成功完毕就调用- (void*)request//注意:应当在控制器被销毁的时候,取消请求[request clearDelegatesAndCancel];
The SEL callback for ASI
@property (atomic, assign) SEL didStartSelector;@property (atomic, assign) SEL didReceiveResponseHeadersSelector;@property (atomic, assign) SEL willRedirectSelector;@property (atomic, assign) SEL didFinishSelector;@property (atomic, assign) SEL didFailSelector;@property (atomic, assign) SEL didReceiveDataSelector;
The ASI Block callback
-(void)Setstartedblock:(asibasicblock)astartedblock;-(void)Setheadersreceivedblock:(asiheadersblock)areceivedblock;-(void)Setcompletionblock:(asibasicblock)acompletionblock;-(void)Setfailedblock:(asibasicblock)afailedblock;-(void)Setbytesreceivedblock:(asiprogressblock)abytesreceivedblock;-(void)Setbytessentblock:(asiprogressblock)abytessentblock;-(void)Setdownloadsizeincrementedblock:(asisizeblock)adownloadsizeincrementedblock;-(void)Setuploadsizeincrementedblock:(asisizeblock)anuploadsizeincrementedblock;-(void)Setdatareceivedblock:(asidatablock)areceivedblock;-(void)Setauthenticationneededblock:(asibasicblock)anauthenticationblock;-(void)Setproxyauthenticationneededblock:(asibasicblock)aproxyauthenticationblock;-(void)Setrequestredirectedblock:(asibasicblock)Aredirectblock;typedef void(^asibasicblock)(void); typedef void(^asiheadersblock)(nsdictionary *responseHeaders); typedef void(^asisizeblock)(long long size); typedef void(^asiprogressblock)(unsigned long long size, unsigned long long total); typedef void(^asidatablock)(nsdata *data);
Get the response from the server
//获得状态码\状态信息@propertyassign,readonlyint responseStatusCode;@property (atomic, retain,readonlyNSString *responseStatusMessage;//获得响应头@propertyNSDictionary *responseHeaders;//获得实体内容(响应体)- (NSData *)responseData;- (NSString *)responseString;
Send a POST request
包含头文件:#import "ASIFormDataRequest.h"// 1.创建请求NSURL *url = [NSURL URLWithString:@"http://192.168.1.103:8080/Server/login"];ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];// 2.设置请求参数[request addPostValue:@"123" forKey:@"username"];[request addPostValue:@"123" forKey:@"pwd"];// 注意addPostValue和setPostValue的区别
File Upload
Asiformdatarequest *request = [Asiformdatarequest Requestwithurl:url];//Add normal request Parameters[Request addpostvalue:@"MJ"forkey:@"username"];//Add File ParametersNSString*file = [[NSBundleMainbundle] pathforresource:@"Musicplayer.png"OfType:Nil]; [Request Addfile:file forkey:@"File"];//orUIImage*image = [UIImageimagenamed:@"Musicplayer"]; NSData *data = uiimagepngrepresentation (image); [Request Adddata:data withfilename:@"Test.png"andcontenttype:@"Image/png"forkey:@"File"]; have2Ways to add File parameters//through the full path of the file- (void) AddFile: (NSString*) FilePath Forkey: (NSString*) key-(void) AddFile: (NSString*) FilePath Withfilename: (NSString*) FileName Andcontenttype: (NSString*) ContentType Forkey: (NSString*) key//through the specific data of the file- (void) AddData: (ID) Data withfilename: (NSString*) FileName Andcontenttype: (NSString*) ContentType Forkey: (NSString*) key
File download
// 设置缓存路径NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];NSString *filepath = [caches stringByAppendingPathComponent:@"test.mp4"];request.downloadDestinationPath = filepath;// 设置下载代理request.downloadProgressDelegate = self.progressView;大文件支持断点续传// 设置文件的临时路径request.temporaryFileDownloadPath = tmpFilepath;// 设置支持断点续传request.allowResumeForFileDownloads = YES;
Monitor file upload \ Download progress
//成为ASI的代理- (void)setUploadProgressDelegate:(id)newDelegate//遵守ASIProgressDelegate协议,实现协议方法- (void)setProgress:(float)newProgress;
Cache

The ASI also provides data caching capabilities
It caches only the response data for GET requests
The cached data must be a successful 200 request
Using the Asidownloadcache class to manage caching

Common Asidownloadcache Usage

//取得默认的缓存对象ASIDownloadCache *cache = [ASIDownloadCache sharedCache];//设置缓存策略- (void)setDefaultCachePolicy:(ASICachePolicy)cachePolicy//设置缓存路径- (void)setStoragePath:(NSString *)path

Cache policy: When to cache, how to use the cached data. Use combinations available
Default Cache policy: If there is no stale cached data, use the cache, otherwise make a network request to determine if the server version is the same as the local version, and if so, use the cache. If the server has a new version, it makes a network request and

//新本地缓存ASIUseDefaultCachePolicyASIAskServerIfModifiedWhenStaleCachePolicy//与默认缓存大致一样,区别仅是每次请求都会 去服务器判断是否有更新ASIAskServerIfModifiedCachePolicy不读取缓存数据//ASIDoNotReadFromCacheCachePolicy//不缓存数据,不写缓存ASIDoNotWriteToCacheCachePolicy//如果有缓存,不管其过期与否,总会拿来使用,没有缓存就重新请求ASIOnlyLoadIfNotCachedCachePolicy//有缓存,拿来使用,如果没有缓存,请求将被取消(没有错误信息)ASIDontLoadCachePolicy//请求失败时,如果有缓存则返回缓存(经常被用来与其它选项组合使用)ASIFallbackToCacheIfLoadFailsCachePolicy
Cache a Request
// 设置缓存策略| ASIFallbackToCacheIfLoadFailsCachePolicy];// 使用缓存[request setDownloadCache:cache];// 设置缓存的存储策略(永久存储)[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];// 设置缓存策略| ASIFallbackToCacheIfLoadFailsCachePolicy];// 使用缓存[ASIHTTPRequest setDefaultCache:cache];
Other usage
现在是否有网络请求在处理中[ASIHTTPRequest isNetworkInUse];当正在请求时,是否要在状态栏显示联网状态(转圈圈)[ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:YES];当应用后台运行时,是否仍然继续处理网络请求request.shouldContinueWhenAppEntersBackgroundYES;设置请求超时后重试的次数request.numberOfTimesToRetryOnTimeout2// 重试2次

iOS Development-HTTP Terminator "ASI"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.