IPhoneApplication Development in progressASIHTTPRequestThe details are the content to be explained in this article,ASIHTTPRequestIs an extremely powerful open-source HTTP access project. Allows simple APIs to complete complex functions, such as asynchronous requests, queue requests, GZIP compression, cache, resumable data transfer, progress tracking, file uploading, and HTTP authentication. In the new version, we also added support for Objective-C closure blocks, making our code simple and flexible.
The following is an example of its API usage.
Initiate a synchronization request
Synchronization means thread blocking. Using this method in the main thread will hold the application Hang without responding to any user event. Therefore, in application design, most of them are used in specialized sub-threads to increase user experience, or use asynchronous requests instead of the ones 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];
- }
- }
Use the requestWithURL shortcut to obtainASIHTTPRequestAn instance
StartSynchronous method to start synchronous access
Because it is a synchronous request and there is no event-based callback method, the error information is obtained from the error attribute of the request.
ResponseString, which is the NSString information returned by the request.
Create an asynchronous request
The advantage of asynchronous requests is that they do not block the current thread, but are slightly more complex than synchronous requests. At least two callback methods must be added to obtain asynchronous events. 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];
- }
Different from the above, a "delegate" is specified and startAsynchronous is used to start the network request.
Two delegate methods are implemented here. When a data request is successful, requestFinished is called. If a request fails, such as a network problem or an internal server error, requestFailed is called.
Queue request
Provides more precise and rich control over asynchronous requests. For example, you can set the number of connections for Synchronous 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 of the preceding requests is completed and columns are placed in the queue for execution. This also applies when we have multiple request needs to be executed in order, which may be business needs or software tuning ), you only need to set 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 execution task NSOperation of the Cocoa architecture) task queue. We can see from the source code of ASIHTTPRequest. h that this class itself is a subclass of NSOperation. In other words, it can be directly put into the "task queue" and executed. The above Code except the creation and addition operations of the queue, is the same as the previous code.
Tips for retrieving or recognizing different requests in an asynchronous queue request
You can set a context userInfo) to the request object. After the request response is complete, you can obtain the information in the request object through userInfo.
Set different setDidFinishSelector/setDidFailSelector callback methods for each request instance
SubclassASIHTTPRequest, Override requestFinished: And failWithProblem: Method
ASINetworkQueues, whose delegate provides richer Functions
More callback methods are provided as follows:
- RequestDidStartSelector: This method is called when a request is initiated. In this method, you can set the deleaget of the request object according to the business selectivity.
- RequestDidReceiveResponseHeadersSelector. After receiving the response Header, design this method. This method is very useful for downloading big data. You can perform more business processing in the method.
- RequestDidFinishSelector. This method is called when the request and response are successful.
- RequestDidFailSelector, request failed
- QueueDidFinishSelector. This method is called when all requests in the queue end.
It is a small and powerful NSOperationQueues extension. But it is also slightly different from its parent class. For example, a request cannot be executed only when it is added to the queue. Only [queue g o] is called. A running queue does not need to call [queue go] repeatedly. By default, if a request in the queue fails, it will cancel all unfinished requests. You can set [queue setShouldCancelAllRequestsOnFailure: NO.
Cancel asynchronous request
First, the synchronization request cannot be canceled.
Second, whether it is a queue request or a simple asynchronous request, all call [request cancel] to cancel the request. By default, all canceled requests are processed based on request failure and the request fails to be called by delegate.
If you do not want to call the delegate method, set: [request clearDelegatesAndCancel];
Note that if you cancel a request, the queue will automatically cancel all other requests. If you only want to cancel a request, you can set the queue:
- [ queue setShouldCancelAllRequestsOnFailure:NO ];
If you want to explicitly cancel all requests: [queue cancelAllOperations];
Safe memory recovery suggestions
The request does not have a retain of your delegate, so the delegate is released when the request is not complete. You need to cancel all requests in the dealloc method before releasing the request instance, for example:
- - (void)dealloc
- {
- [request clearDelegatesAndCancel];
- [request release];
- ...
- [super dealloc];
- }
Upload data to the server
ASIFormDataRequest: simulates Form submission. The submission format and Header are automatically recognized.
No file: application/x-www-form-urlencoded
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"];
To send custom data:
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- [request appendPostData:[@"This is my data" dataUsingEncoding:NSUTF8StringEncoding]];
- // Default becomes POST when you use appendPostData: / appendPostDataFromFile: / setPostBody:
- [request setRequestMethod:@"PUT"];
Download files
You can set the target directory for downloading files by setting the setDownloadDestinationPath of the request.
First, the downloaded file is saved in the temporaryFileDownloadPath directory. If the download is complete, do the following:
If the data is compressed, decompress the package and put the file in the downloadDestinationPath directory. The temporary file is deleted.
If the download fails, the temporary file is directly moved to the downloadDestinationPath directory, and the file with the same name is replaced.
If you want to obtain all the data downloaded, You can implement the request: didReceiveData: Method in delegate. However, if you have implemented this method, after the request is downloaded, the request does not put the file in downloadDestinationPath and needs to be processed manually.
Get Response Information
Information: 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:
- DownloadProgressDelegate to get the download progress
- UploadProgressDelegate to get the upload progress
Cookie support
If the Cookie exists, the information will be shared in the NSHTTPCookieStorage container for the next use. You can use [ASIHTTPRequest setSessionCookies: nil]; to clear all Cookies. Of course, you can also cancel the default Cookie policy to enable custom cookies:
- //Create a cookie
- NSDictionary *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 will return the value of the 'ASIHTTPRequestTestCookie' cookie
- url = [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 have 'Test Value' as the value of 'ASIHTTPRequestTestCookie'
- NSLog(@"%@",[request responseString]);
Resumable upload of large files after 0.94 supports resumable download of large files. You only need to set
- [ request setAllowResumeForFileDownloads:YES ];
- [ request setDownloadDestinationPath:downloadPath ];
You can.
Summary:IPhoneApplication Development in progressASIHTTPRequestThe detailed description is complete. I hope you can learn this article to help you!