Network Programming-ASI -- (ASIHTTPRequest) Introduction, cnetwork programming Introduction

Source: Internet
Author: User

Network Programming-ASI -- (ASIHTTPRequest) Introduction, cnetwork programming Introduction

Although ASIHTTPRequest is about tomorrow, I would like to summarize it a little and clarify my ideas to find out what she was able to do.

 

1. The ASI is based on the underlying CFNetworking framework and runs very efficiently.

2. prime partner: ASI + SBJson, which is used for network requests and SBJson for parsing data returned by the server.

3. For more information about ASI, see:

1> Bao Yu's blog:

Http://www.cnblogs.com/dotey/archive/2011/05/10/2041966.html 2> oxchina.net open source China Community http://www.oschina.net/question/54100_36184

 

 

Basic usage:

1. Send a synchronization request;

Contains the main file # import "ASIHTTPRequest. h" // 1. Create a request NSURL * url = [NSURL URLWithString: @ "http: // 192.168.1.111: 8080/XZServer/login? Username = 123 & pwd = 123 "]; ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL: url]; request. timeOutSeconds = 5; // timeout // 2. send a synchronous request [request startSynchronous]; // 3. obtain the error message NSError * error = [request error]; if (error) {NSLog (@ "error ");} else {// obtain the server response NSData * data = [request responseData];} // [request responseData]

 

2. Send an asynchronous request;

// 1. Create a request NSURL * url = [NSURL URLWithString: @ "http: // 192.168.1.103: 8080/XZServer/login? Username = 123456 & pwd = 123456 "]; ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL: url]; request. timeOutSeconds = 5; // timeout // 2. set proxy request. delegate = self; // 3. send an asynchronous request [request startAsynchronous]; // ASI processes the asynchronous request by proxy. If the request succeeds or fails, the proxy is notified. // The proxy must comply with the ASIHTTPRequestDelegate protocol.

 

3. ASIHTTPRequestDelegate:

When receiving the server data, call-(void) request :( ASIHTTPRequest *) request didReceiveData :( NSData *) when the data request fails, call-(void) requestFailed :( ASIHTTPRequest *) after the request is successful, call-(void) requestFinished :( ASIHTTPRequest *) request Note: When the controller is destroyed, cancel the request [request clearDelegatesAndCancel];

 

SEL callback of 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;

 

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);

 

Obtain the server response:

Get Status Code \ status information @ property (atomic, assign, readonly) int responseStatusCode; @ property (atomic, retain, readonly) NSString * responseStatusMessage; Get Response Header @ property (atomic, retain) NSDictionary * responseHeaders; get the object content (response body)-(NSData *) responseData;-(NSString *) responseString;

 

Send POST request:

Include header file: # import "ASIFormDataRequest. h "// 1. create a request NSURL * url = [NSURL URLWithString: @ "http: // 192.168.1.103: 8080/XZServer/login"]; ASIFormDataRequest * request = [ASIFormDataRequest requestWithURL: url]; // 2. set the request parameter [request addPostValue: @ "123" forKey: @ "username"]; [request addPostValue: @ "123" forKey: @ "pwd"]; // note the difference between addPostValue and setPostValue

 

File Upload:

ASIFormDataRequest * request = [ASIFormDataRequest requestWithURL: url]; // Add a common request parameter [request addPostValue: @ "MJ" forKey: @ "username"]; // Add the file parameter NSString * file = [[NSBundle mainBundle] pathForResource: @ "musicplayer.png" ofType: nil]; [request addFile: file forKey: @ "file"]; // or UIImage * image = [UIImage imageNamed: @ "musicplayer"]; NSData * data = UIImagePNGRepresentation (image); [request addData: data withFileName: @ "test.png" andContentType: @ "image/png" forKey: @ "file"];

File Upload-add file Parameters

There are two ways to add file parameters: 1> use 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 *) key2> addData :( id) data withFileName :( NSString *) fileName andContentType :( NSString *) contentType forKey :( NSString *) key

 

 

File Download:

// Set the cache path NSString * caches = [Response (NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString * filepath = [caches stringByAppendingPathComponent: @ "test.mp4"]; request. downloadDestinationPath = filepath; // sets the download proxy request. downloadProgressDelegate = self. progressView; supports resumable upload of large files // sets the temporary file path request. temporaryFileDownloadPath = tmpFilepath; // supports resumable upload request. allowResumeForFileDownloads = YES;

Listener file upload/download progress

Become the ASI proxy-(void) setUploadProgressDelegate :( id) newDelegate complies with the ASIProgressDelegate protocol and implements the Protocol method-(void) setProgress :( float) newProgress;

 

Cache:

ASI also provides the data cache function. It only caches the response data of Get requests. The cached data must be successful. 200 of requests use the ASIDownloadCache class to manage cache. Common ASIDownloadCache usage: obtaining default cache objects ASIDownloadCache * cache = [ASIDownloadCache sharedCache]; set Cache Policy-(void) setDefaultCachePolicy :( ASICachePolicy) cachePolicy set cache path-(void) setStoragePath :( NSString *) path

 

Cache Policy-ASICachePolicy

Cache Policy: When to cache and how to use cached data. Use the default Cache Policy for combination: If cache data has not expired, use the cache; otherwise, make a network request to determine whether the server version is the same as the local version. If the server version is the same, use the cache.
If a new version is available on the server, a network request is sent and the local cache asiusedefaultcache+yasiaskserverifmodifiedwhenstalecachepolicy is roughly the same as the default cache, the difference is that each request will go to the server to determine whether there is an update ASIAskServerIfModifiedCachePolicy that does not read cached data ASIDoNotReadFromCacheCachePolicy does not cache data. If there is a cache, no matter whether it expires or not, it will be, if no cache is available, request ASIOnlyLoadIfNotCachedCachePolicy for use again. If no cache is available, the request will be canceled (no error message) when the ASIDontLoadCachePolicy request fails, if there is a cache, return the cache (often used in combination with other options) ASIFallbackToCacheIfLoadFailsCachePolicy

 

Cache a request:

// Set the cache Policy ASIDownloadCache * cache = [ASIDownloadCache sharedCache]; [cache setDefaultCachePolicy: ASIOnlyLoadIfNotCachedCachePolicy | cached]; // use the cache [request setDownloadCache: cache]; // set the cache storage policy (permanent storage) [request setCacheStoragePolicy: ASICachePermanentlyCacheStoragePolicy];

 

 

Storage Policy of ASIHTTPRequest Cache

Cache storage policy: the Default policy for how long the cache needs to be stored. session-based Cache data storage will expire when the next operation or [ASIHTTPRequest clearSession) ASICacheForSessionDurationCacheStoragePolicy the cached data is permanently stored locally (in the hard disk cache) ASICachePermanentlyCacheStoragePolicy

 

Cache all requests:

// Set the cache Policy ASIDownloadCache * cache = [ASIDownloadCache sharedCache]; [cache setDefaultCachePolicy: ASIOnlyLoadIfNotCachedCachePolicy | cached]; // use the cache [ASIHTTPRequest setDefaultCache: cache];

 

Other caching features:

Set the cache validity period [request setSecondsToCache: 60*60*24*7]; // determines whether the data is read from the cache for 7 days BOOL useCache = [request didUseCachedResponse];

 

Other features of ASIHTTPRequest:

In fact, ASIHTTPRequest inherits from NSOperation, which means that multiple ASIHTTPRequest can be put into NSOperationQueue, and multiple requests can be managed at the same time to set dependencies between requests... ... ASIFormDataRequest inherited from ASIHTTPRequest

 

Other usage:

Whether a network request is being processed [ASIHTTPRequest isNetworkInUse]; Whether to display the network status (circled) in the status bar when the request is being processed [ASIHTTPRequest setShouldUpdateNetworkActivityIndicator: YES]; when the application is running in the background, whether to continue to process the network request. shouldContinueWhenAppEntersBackground = YES; set the number of retries after request timeout request. numberOfTimesToRetryOnTimeout = 2; // retry twice

 

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.