asi--(asihttprequest) Introduction

Source: Internet
Author: User

ASIHTTPRequest Although is the past, but still a little summed up, clear the idea, know this once she is able to do.

1. ASI is based on the underlying cfnetworking framework and is highly efficient.

2. Gold Partner: ASI + Sbjson, ASI is used for network requests, and Sbjson is used to parse the data returned by the server.

Reference for use of 3.ASI:

1> Baoyu'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 use:

1. Send a sync request;

Include the main file#import "ASIHTTPRequest.h"//1. Create a requestNsurl *url = [Nsurl urlwithstring:@"http://192.168.1.111:8080/XZServer/login?username=123&pwd=123"]; ASIHTTPRequest*request =[ASIHTTPRequest requestwithurl:url];request.timeoutseconds=5;//timed out//2. Send a sync request[Request startsynchronous];//3. Get the error messageNserror *error =[Request ERROR];if(Error) {NSLog (@"something went wrong.");} Else {    //get the response from the serverNSData *data =[Request ResponseData];} //[Request ResponseData]

2. Sending an asynchronous request;

//1. Create a requestNsurl *url = [Nsurl urlwithstring:@"http://192.168.1.103:8080/XZServer/login?username=123456&pwd=123456"]; ASIHTTPRequest*request =[ASIHTTPRequest requestwithurl:url];request.timeoutseconds=5;//timed out//2. Setting up the agentRequest.Delegate=Self ;//3. Sending an asynchronous request[Request startasynchronous];//ASI handles asynchronous requests through proxies, which notify the broker if a request succeeds or fails//agents are required to comply with the Asihttprequestdelegate protocol

3.ASIHTTPRequestDelegate:

Call-(void) request for data received from the server : (asihttprequest *) Request Didreceivedata: (NSData *) data The request failed to invoke  -(void) requestfailed: (ASIHTTPRequest *) The request was successfully completed on call  -(void ) requestfinished: (ASIHTTPRequest *) request Note: Cancellation of requests should be made when the controller is destroyed [requesting 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;typedefvoid(^asibasicblock) (void); typedefvoid(^asiheadersblock) (Nsdictionary *responseheaders); typedefvoid(^asisizeblock) (Long Longsize); typedefvoid(^asiprogressblock) (unsignedLong LongSize, unsignedLong LongTotal ); typedefvoid(^asidatablock) (NSData *data);

Get the response from the server:

get status code \ Status information @property (Atomic, assign,readonlyint  responsestatuscode; @property ( Atomic, retain,readonly) NSString *responsestatusmessage;  Get response header  *responseheaders;  Get entity content (response body)-(NSData *) responsedata; -(NSString *) responsestring;

To send a POST request:

Include Header files:#import "ASIFormDataRequest.h"//1. Create a requestNsurl *url = [Nsurl urlwithstring:@"Http://192.168.1.103:8080/XZServer/login"]; Asiformdatarequest*request =[Asiformdatarequest Requestwithurl:url];//2. Set Request Parameters[Request Addpostvalue:@"123"Forkey:@"username"]; [Request Addpostvalue:@"123"Forkey:@"pwd"];//Notice the difference between Addpostvalue and Setpostvalue.

File Upload:

Asiformdatarequest *request =[Asiformdatarequest Requestwithurl:url];//add a normal request parameter[Request Addpostvalue:@"MJ"Forkey:@"username"];//Add File ParametersNSString *file = [[NSBundle mainbundle] Pathforresource:@"Musicplayer.png"Oftype:nil]; [Request Addfile:file Forkey:@"file"];//orUIImage *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 2 ways to add File parameters: 1> 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 *) key2> specific data via file -(void) AddData: (ID) data Withfilename: (NSString *) fileName andcontenttype: (NSString *) ContentType forkey: (NSString *) key

File Download:

//set the cache pathNSString *caches =[Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastobject]; NSString*filepath = [Caches stringbyappendingpathcomponent:@"Test.mp4"];request.downloaddestinationpath=filepath;//set up Download AgentRequest.downloadprogressdelegate =Self.progressview; Large files support breakpoint continuation//set a temporary path for a fileRequest.temporaryfiledownloadpath =Tmpfilepath;//set support for breakpoint continuationRequest.allowresumeforfiledownloads = YES;

Monitor file upload \ Download progress

become an agent of ASI -(void) Setuploadprogressdelegate: (ID) newdelegate  Comply with ASIPROGRESSDELEGATE protocol, implement protocol method  -(void) setprogress: (float) newprogress;

Cache:

ASI also provides data caching capabilities that cache data that is cached only for the response data of a GET request must be a successful 200 request to use the Asidownloadcache class to manage the cache Common Asidownloadcache usage get the default cache object  *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, how to use the cached data. The default cache policy can be used in combination: if there is no stale cache data, the cache is used, otherwise a network request is made to determine if the server version is the same as the local version, and if so, the cache is used.
If the server has a new version, it makes a network request and updates the local cache Asiusedefaultcachepolicyasiaskserverifmodifiedwhenstalecachepolicy is roughly the same as the default cache, except that each request will go to the server to determine if there is an update Asiaskserverifmodifiedcachepolicy does not read cache data Asidonotreadfromcachecachepolicy does not cache data, does not write cache Asidonotwritetocachecachepolicy If there is a cache, regardless of whether it expires or not, will always be used, no cache to re-request Asionlyloadifnotcachedcachepolicy have cache , which is used, if there is no cache, the request will be canceled (no error message)If the Asidontloadcachepolicy request fails, the cache is returned if there is a cache (often used in combination with other options) Asifallbacktocacheifloadfailscachepolicy

To cache a request:

// Set Cache policy Asidownloadcache *cache =| Asifallbacktocacheifloadfailscachepolicy]; // using the Cache [Request Setdownloadcache:cache]; // set the cache's storage policy (persistent storage) [Request Setcachestoragepolicy:asicachepermanentlycachestoragepolicy];

Storage policies for ASIHTTPRequest cache

Cached Storage Policy: How long the cache needs to be saved The default policy, session-based cache data storage, when next run or [ASIHTTPRequest clearsession], Cache is invalidated (memory cached) Asicacheforsessiondurationcachestoragepolicy cache data is persisted locally (hard disk cache) Asicachepermanentlycachestoragepolicy

Cache all requests:

// Set Cache policy Asidownloadcache *cache =| Asifallbacktocacheifloadfailscachepolicy]; // using the Cache [ASIHTTPRequest Setdefaultcache:cache];

Other features of the cache:

set the expiration date of the cache [Request Setsecondstocache:  -  -  - 7 // cached for 7 days determines whether the data is read from the cache = [request Didusecachedresponse];

ASIHTTPRequest Other Features:

In fact ASIHTTPRequest inherit from nsoperationasihttprequest into nsoperationqueue , Managing multiple requests at the same time can set dependencies between requests ... Asiformdatarequest inherited from ASIHTTPRequest

Other uses:

Is there a network request in process now ? [ASIHTTPRequest Isnetworkinuse]; whether to display the networking status in the status bar when the request is being requested (turn circle) [ASIHTTPRequest Setshouldupdatenetworkactivityindicator:yes]; whether the network request continues to process while the app is running in the background  = YES; to set the number of retries after a request times out  2 // Retry 2 times

asi--(asihttprequest) Introduction

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.