(ext.) IOS ASI HTTP Framework Detailed

Source: Internet
Author: User

(ext.) IOS ASI HTTP Framework Detailed

The ASIHTTPRequest Cfnetwork API is encapsulated and very simple to use, written in objective-c, and can be used in Mac OS x systems and iOS applications. ASIHTTPRequest applies to basic HTTP requests, and to the interaction between rest-based services.

ASIHTTPRequest features are very powerful, the main features are as follows:

L can submit data to the server and get the data from the server by simple interface. l Download data that can be stored in memory or stored directly on disk L can upload a local file to the server L can easily access and manipulate the request and return the HTTP header information L could get to upload or download progress information, Provide a better experience for your application l support upload or download queues, and get progress information for queues L support Basic, Digest, and NTLM authentication, the authorization credentials are automatically maintained in the same session, and can be stored in the keychain (Mac and iOS operating system Password management system) L Support Cookie L when the app (IOS 4+) is running in the background, the request can continue to run L support gzip compressed data l built-in Asidownloadcache class that can cache the data returned by the request so that even if no network can return the cached data results l asiwebpagerequest– can download the complete Web page, including the included Web page, style sheet, script and other resource files, and display in the Uiwebview/webview. Pages of any size can be cached indefinitely, so that you can browse offline without a network L support client certificate L support HTTP request via proxy l support bandwidth throttling. On the iOS platform, you can automatically decide whether to limit bandwidth based on current network conditions, such as when using Wwan (GPRS/EDGE/3G) networks, and when WiFi is not limited L support for synchronous and asynchronous requests

1) Add File

There are two ways to add a third-party class library file to a Xcode project:

1. The first way, open in the Finder you need to add to a file or folder, open the item in Xcode that you want to add a file to, and then select the file or folder you want to add, drag it from the Finder to Xcode, and then release. In the popup dialog box, if the file has been copied to the project file directory, you do not need to check the "Copy items" checkbox, or if the file is not copied to the project file directory, you will need to select the "Copy Items" check box so that Xcode will automatically copy the files to the project file directory. As shown in the following:

2. The second way, in Xcode, right-click the group under which you want to add the file, select the "Add Files to" My Project ... menu, and in the pop-up file Browse dialog box, choose the file or folder you want to add. If you want to add a file that has been copied to the project file directory, you do not need to select the check box for copy items, or if the file is not copied to the project file directory, you need to select the "Copy Items" check box so that Xcode automatically copies the files to the project file directory. As shown in the following:

Based on the instructions above, add asihttprequest related files to the Xcode project with the following list of required files:

ASIHTTPRequestConfig.h

ASIHTTPRequestDelegate.h

ASIProgressDelegate.h

ASICacheDelegate.h

ASIHTTPRequest.h

Asihttprequest.m

ASIDataCompressor.h

Asidatacompressor.m

ASIDataDecompressor.h

Asidatadecompressor.m

ASIFormDataRequest.h

ASIInputStream.h

Asiinputstream.m

Asiformdatarequest.m

ASINetworkQueue.h

Asinetworkqueue.m

ASIDownloadCache.h

Asidownloadcache.m

ASIAuthenticationDialog.h

Asiauthenticationdialog.m

Reachability.h (under the external/reachability directory of the source code)

REACHABILITY.M (under the external/reachability directory of the source code)

2) Link related class library

1. Select the item

2. Select the target

3. Jump to the "Build Phases" tab

4. Expand the "Link Binary with Libraries" grouping

5. Click "+" to add the class library

As shown in the following:

6. Select Cfnetwork.framework from the list and click the "Add" button.

7. Follow the same method as in the previous step to add: Systemconfiguration.framework, Mobilecoreservices.framework, Coregraphics.framework and Libz.1.2.3.dylib are some of the class libraries.

8. Once added, you can drag the added class library into the frameworks directory of the Xcode project


Before using ASIHTTPRequest, make sure that you have installed it correctly, and then add it to the header of the code file that you want to apply it to:

#import "ASIHTTPRequest.h"

This allows you to use ASIHTTPRequest related classes in your code.

Initiate a synchronization request

Synchronization is meant to block threads, and using this method in the main thread causes the app to hang without responding to any user events. Therefore, in application design, most are used in specialized sub-threads to increase the user experience, or to use asynchronous requests instead (as described below).

-(Ibaction) Graburl: (ID) sender{Nsurl *url = [Nsurl urlwithstring:@ "http://allseeing-i.com"];  ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url];  [Request startsynchronous];  Nserror *error = [request ERROR];  if (!error) {nsstring *response = [request responsestring]; }}

A, using Requestwithurl shortcut method to get an example of asihttprequest
B, the Startsynchronous method initiates synchronous access,
C, because it is a synchronous request, there is no event-based callback method, so the error message is obtained from the request's error property.
D, responsestring, returns nsstring information for the request.

Create an asynchronous request

The benefit of an asynchronous request is that it does not block the current thread, but is slightly more complex than the synchronization request, adding at least two callback methods to get the asynchronous event.
The following asynchronous request code completes the same thing:

-(Ibaction) Graburlinbackground: (ID) sender{Nsurl *url = [Nsurl urlwithstring:@ "http://allseeing-i.com"];   ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url];   [Request Setdelegate:self]; [Request startasynchronous];} -(void) requestfinished: (ASIHTTPRequest *) request{//Use when fetching text data nsstring *responsestring = [request    Responsestring]; Use when fetching binary data nsdata *responsedata = [request ResponseData];} -(void) requestfailed: (ASIHTTPRequest *) request{nserror *error = [request ERROR];}

A, unlike above, a "delegate" is specified, and a startasynchronous is used to initiate a network request.
b, two delegate methods are implemented here, and when the data request succeeds, the requestfinished is called, and the request fails (such as a network problem or an internal server error) that calls requestfailed.

Queue Request

The

Provides a more granular control over asynchronous requests.
For example, you can set the number of connections to synchronize requests in the queue. When the number of request instances added to the queue is greater than Maxconcurrentoperationcount, the request instance is set to wait until at least one request is completed and the dequeue is placed in the queue for execution. The
also applies when we have multiple request requests executed sequentially (either business or software tuning), just set the Maxconcurrentoperationcount to "1".

-(Ibaction) Graburlinthebackground: (ID) sender{   if (![ Self queue]) {      [self Setqueue:[[[nsoperationqueue alloc] init] autorelease]];    }    nsurl *url = [Nsurl urlwithstring:@ " http://allseeing-i.com"];    asihttprequest *request = [ASIHTTPRequest requestwithurl:url];   [request Setdelegate:self];   [request setdidfinishselector: @selector (requestdone:)];   [ Request Setdidfailselector: @selector (requestwentwrong:)];   [[self queue] addoperation:request];  //queue is an nsoperationqueue} -(void) Requestdone: (ASIHTTPRequest *) request{   nsstring *response = [request responsestring];}  -(void) Requestwentwrong: (ASIHTTPRequest *) request{   nserror *error = [request ERROR];}

Create Nsoperationqueue, the task queue for the Cocoa architecture's execution Task (nsoperation). We can see through the source code of ASIHTTPRequest.h that this class is itself a nsoperation subclass. This means that it can be placed directly in the "task queue" and executed. The above code team the queue is created and added in addition to the other code as in the previous example.

Request Queue Context

A, you can set a context (UserInfo) into the Request object, and then you can get the information inside by accessing the userInfo of the requester object when the response is complete.
b, set a different Setdidfinishselector/setdidfailselector callback method for each request instance
C, subclass ASIHTTPRequest, rewrite requestfinished: With Failwithproblem: Method

Asinetworkqueues, its delegate provides richer functionality

More callback methods are provided as follows:
A,requestdidstartselector, this method is called when the request is initiated, and you can set the Deleaget of the request object in this method, according to the business selectivity.
B,requestdidreceiveresponseheadersselector, this method is designed when the header of the response is accepted, which is quite useful when downloading big data, and you can do more business processing in the method.
C,requestdidfinishselector, call this method when the request and response completes successfully
D,requestdidfailselector, request failed
E,queuedidfinishselector, this method is called at the end of all requests in the entire queue.

It is an extension of nsoperationqueues, small and powerful. But it's also slightly different from its parent class. For example, only adding to the queue does not actually execute the request, only the [Queue G O] is invoked, and a running queue does not need to be called repeatedly [queue go].

By default, if a request in a queue fails, it cancels all outstanding requests. You can set [queue Setshouldcancelallrequestsonfailure:no] to fix.

Canceling an asynchronous request

First, the synchronization request cannot be canceled.
Second, whether it is a queue request, or a simple asynchronous request, all calls [request Cancel] to cancel the request.

Canceled requests are processed by default on request, and the request fails to be called delegate.
If you do not want to call the delegate method, set: [Request Cleardelegatesandcancel];

Note in the queue request that if you cancel a request, the queue automatically cancels all other requests.
If you want to cancel only one request, you can set the queue: [Queue Setshouldcancelallrequestsonfailure:no];
If you want to explicitly cancel all requests: [Queue cancelalloperations];

Safe Memory Recycling Recommendations

The request does not retain your delegate, so if you release this delegate when there is no request, you need to cancel all requests in the Dealloc method before releasing the requested instance, such as:

-(void) dealloc{[request Cleardelegatesandcancel];   [Request release];   ... [Superdealloc];}

Uploading data to server side

Asiformdatarequest, simulate form submission, its submission format and header will be automatically recognized.
No files: application/x-www-form-urlencoded
There are files: Multipart/form-data

Asiformdatarequest *request = [Asiformdatarequest Requestwithurl:url]; [Request setpostvalue:@ "Ben" forkey:@ "first_name"]; [Request setpostvalue:@ "Copsey" forkey:@ "last_name"]; [Request setfile:@ "/users/ben/desktop/ben.jpg" forkey:@ "photo"]; [Request Adddata:imagedata withfilename:@ "george.jpg" andcontenttype:@ "image/jpeg" forkey:@ "photos"];

If you want to send custom data:

ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url]; [Request appendpostdata:[@ "This is my data" datausingencoding:nsutf8stringencoding]];//Default becomes POST Appendpostdata:/appendpostdatafromfile:/setpostbody:[request setrequestmethod:@ "PUT"];

Download file

By setting the Setdownloaddestinationpath of the request, you can set the download destination directory for the downloaded file.
First, the download process files are saved in the Temporaryfiledownloadpath directory. If the download completes, the following things will be done:
1, if the data is compressed, unzip, and put the file in the Downloaddestinationpath directory, temporary files are deleted
2, if the download fails, the temporary file is moved directly to the Downloaddestinationpath directory and replaces the file with the same name.

If you want to get all the data in the download, you can implement the Request:didreceivedata: Method in Delegate. But if you implement this method, the request does not put the file in the Downloaddestinationpath after downloading, and it needs to be handled manually.

Get response information

Info: status, header, responseencoding

[Request Responsestatuscode]; [Request Responseheaders] objectforkey:@ "x-powered-by"]; [Request responseencoding];

Get Request Progress

There are two callback methods to get the request progress,
1,downloadprogressdelegate, you can get the download progress
2,uploadprogressdelegate, you can get upload progress

Support for Cookies

If the cookie exists, it will be shared in the Nshttpcookiestorage container for the next use.
You can use [ASIHTTPRequest setsessioncookies:nil]; Clear all cookies.
Of course, you can also cancel the default cookie policy and make the custom cookie:

Create a cookiensdictionary *properties = [[[[Nsmutabledictionary alloc] init] autorelease]; [Properties setvalue:[@ "Test Value"  encodedcookievalue] forkey:nshttpcookievalue]; [Properties setvalue:@ "Asihttprequesttestcookie" forkey:nshttpcookiename]; [Properties setvalue:@ ". allseeing-i.com" Forkey:nshttpcookiedomain]; [Properties Setvalue:[nsdate datewithtimeintervalsincenow:60*60] forkey:nshttpcookieexpires]; [Properties setvalue:@ "/asi-http-request/tests" Forkey:nshttpcookiepath]; Nshttpcookie *cookie = [[[Nshttpcookie alloc] initwithproperties:properties] autorelease]; //this URL would return The value of the ' asihttprequesttestcookie ' Cookieurl = [Nsurl urlwithstring:@ '  http://allseeing-i.com/ Asihttprequest/tests/read_cookie "];request = [ASIHTTPRequest Requestwithurl:url]; [Request Setusecookiepersistence:no]; [Request Setrequestcookies:[nsmutablearray Arraywithobject:cookie]; [Request Startsynchronous]; //should be:i has ' Test value ' as the value of ' ASIHTTPREQUESTTESTCOokie ' NSLog (@ "%@", [request responsestring]);

Large File Breakpoint Continuation

0.94 after support for large file breakpoint download, only need to set:
[Request Setallowresumeforfiledownloads:yes];
[Request Setdownloaddestinationpath:downloadpath];
You can do it.

ASIHTTPRequest will automatically save the URL information that has been accessed and is ready for use later. This is useful in several scenarios:
1, when there is no network connection.
2, when the downloaded data is requested again, it is downloaded only if it is not the same as the local version.

Asidownloadcache setting up the download cache

It caches the response data for the GET request (the cached data must be a successful 200 request):

[ASIHTTPRequest Setdefaultcache:[asidownloadcache Sharedcache];

When the cache policy is set, all requests are automatically cached.
Also, if you only want a request to use a cache operation, you can use this:

ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url]; [Request Setdownloadcache:[asidownloadcache Sharedcache];

Multi-cache Coexistence

Just create a different asidownloadcache, set the path used by the cache, and set it to the request instance that you want to use:

Asidownloadcache *cache = [[[[Asidownloadcache alloc] init] autorelease]; [Cache setstoragepath:@ "/users/ben/documents/cached-downloads"]; [Self setmycache:cache]; ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url]; [Request Setdownloadcache:[self Mycache];

Caching policies

Caching policies are the primary way we control caching behavior, such as when to cache and how to use cached data.
The following is an optional list of policies (which can be used in combination):

Asiusedefaultcachepolicy This is a default caching policy "Asiaskserverifmodifiedwhenstalecachepolicy", which is very clear, See the name (it cannot be used in combination with other policies) Asidonotreadfromcachecachepolicy The data read does not use the cache Asidonotwritetocachecachepolicy write to the cached data Asiaskserverifmodifi Edwhenstalecachepolicy The default caching behavior, the request will first determine if the cache data exists. A, if no further network requests are made. b, if there is cached data and the data does not expire, the cache is used. C, if there is cached data, but it has expired, request will make network requests 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 updates the local cache Asiaskserverifmodifiedcachepolicy the same as the default cache, except that each request will Go to the server to determine if there is an update asionlyloadifnotcachedcachepolicy if there is a cache on-premises, regardless of its expiration or not, will always be used to use asidontloadcachepolicy only when there is a cache when the correct execution, If there is no cache, the request will be canceled (no error message) Asifallbacktocacheifloadfailscachepolicy This option is often used in combination with other options. If a request fails, if there is a cache when the network returns local cache information (which is useful when handling exceptions) all requests will use this cache if "Defaultcachepolicy" is set.

How the cache is stored

You can set how long the cached data needs to be saved, and ASIHTTPRequest provides two strategies:
A,asicacheforsessiondurationcachestoragepolicy, default policy, session-based cache data storage. The cache will expire the next time you run or [ASIHTTPRequest clearsession].
B,asicachepermanentlycachestoragepolicy, the cache data is permanently stored locally,
Such as:

ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url]; [Request Setcachestoragepolicy:asicachepermanentlycachestoragepolicy];

Alternatively, you can use Clearcachedresponsesforstoragepolicy to empty the cached data under the specified policy.

Caching Other features

Sets whether the cache or expiration policy can be cached as specified by the server in the header:

[[Asidownloadcache Sharedcache] setshouldrespectcachecontrolheaders:no];

To set the validity time for the request cache:

[Request setsecondstocache:60*60*24*30];//cache for 30 days

You can tell whether the data is read from the cache:

[Request Didusecachedresponse];

To set the path used by the cache:

[Request setdownloaddestinationpath:[[Asidownloadcache Sharedcache] Pathtostorecachedresponsedataforrequest: Request]];

Implementing a custom Cache

As long as the simple implementation of the Asicachedelegate interface can be used.

Using Proxy requests

By default, ASIHTTPRequest uses the default proxy that is set. But you can also manually modify the HTTP proxy:

Configure a proxy server manuallynsurl *url = [Nsurl urlwithstring:@ "Http://allseeing-i.com/ignore"]; ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url]; [Request setproxyhost:@ "192.168.0.1"]; [Request setproxyport:3128]; Alternatively, can use a manually-specified Proxy Auto Config file (PAC)//(It's probably best if your use a local f ile) [Request Setpacurl:[nsurl urlwithstring:@ "File:///Users/ben/Desktop/test.pac"];

ASIHTTPRequest, other features of the request

IOS4, the data is still requested when the app is running in the background:

[Request Setshouldcontinuewhenappentersbackground:yes];

Whether there is a network request:

[ASIHTTPRequest Isnetworkinuse]

Whether to display network request information on status bar:

[ASIHTTPRequest Setshouldupdatenetworkactivityindicator:no];

When setting the request timeout, set the number of retries:

[Request Setnumberoftimestoretryontimeout:2];

KeepAlive's support:

Set The amount of time-to-hang-to-a persistent connection before it should expire to 2 minutes[request Setpersisten TCONNECTIONTIMEOUTSECONDS:120]; Disable Persistent Connections entirely[request Setshouldattemptpersistentconnection:no];

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.