Asihttprequest: http request Terminator ~~ Hey

Source: Internet
Author: User
Tags http authentication
Translate this official document for sharing today ~
Make the lost man have a path to find ~

Asihttprequest is an extremely powerful open-source HTTP access project. Let simple APIs complete complex functions,

For example:
Asynchronous request, queue request, Gzip compression, cache, resumable data transfer, progress tracking, file upload, HTTP Authentication
In the new version, we also added support for objective-C closure blocks, so that ourCodeIt is simpler, simpler, and more flexible.

The following is an example of its API usage.

initiate a synchronization request
synchronization means thread blocking, in the main thread, use . Therefore, in application Program is designed to increase user experience in special subthreads, or use asynchronous requests instead (as described below ).

Copy code

  1. -(Ibaction) graburl :( ID) sender
  2. {
  3. Nsurl * url = [nsurl urlwithstring: @ "http://allseeing-i.com"];
  4. Asihttprequest * request = [asihttprequest requestwithurl: url];
  5. [Request startsynchronous];
  6. Nserror * error = [Request Error];
  7. If (! Error ){
  8. Nsstring * response = [Request responsestring];
  9. }
  10. }

A. Use requestwithurl to obtain an instance of asihttprequest.
B. Start synchronous access in the startsynchronous method,
C. 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.
D, responsestring, which is the nsstring information returned by the request.

creating an asynchronous request
the advantage of an asynchronous request is that it does not block the current thread, but is slightly more complex than a synchronous request, at least two callback methods must be added to obtain asynchronous events.
The following asynchronous request code completes the same thing:

copy the Code

  1. -(ibaction) graburlinbackground :( ID) sender
  2. {
  3. nsurl * url = [nsurl urlwithstring: @ "http://allseeing-i.com"];
  4. asihttprequest * request = [asihttprequest requestwithurl: url];
  5. [Request setdelegate: Self];
  6. [Request startasynchronous];
  7. }
  8. -(void) requestfinished :( asihttprequest *) Request
  9. {
  10. // use when fetching text data
  11. nsstring * responsestring = [Request responsestring];
  12. // use when fetching binary data
  13. nsdata * responsedata = [Request responsedata];
  14. }
  15. -(void) requestfailed :( asihttprequest *) Request
  16. {
  17. nserror * error = [Request Error];
  18. }

A. The difference is that a "delegate" is specified and startasynchronous is used to start the network request.
B. Two delegate methods are implemented here. When a data request is successful, requestfinished is called and the request fails (such as the networkProblemOrServiceInternal error) will call requestfailed.

Queue request
Provides more precise and rich control over asynchronous requests.
For example, you can set the number of 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.
It is also suitable for executing multiple requests in sequence (either business or software tuning ), you only need to set maxconcurrentoperationcount to "1 ".

Copy code

  1. -(Ibaction) graburlinthebackground :( ID) sender
  2. {
  3. If (! [Self queue]) {
  4. [Self setqueue: [[nsoperationqueue alloc] init] autorelease];
  5. }
  6. Nsurl * url = [nsurl urlwithstring: @ "http://allseeing-i.com"];
  7. Asihttprequest * request = [asihttprequest requestwithurl: url];
  8. [Request setdelegate: Self];
  9. [Request setdidfinishselector: @ selector (requestdone :)];
  10. [Request setdidfailselector: @ selector (requestwentwrong :)];
  11. [[Self queue] addoperation: request]; // queue is an nsoperationqueue
  12. }
  13. -(Void) requestdone :( asihttprequest *) Request
  14. {
  15. Nsstring * response = [Request responsestring];
  16. }
  17. -(Void) requestwentwrong :( asihttprequest *) Request
  18. {
  19. Nserror * error = [Request Error];
  20. }

Create nsoperationqueue, the task queue for executing tasks (nsoperation) in the cocoa architecture. 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 team created and added the queue, and other code is the same as the previous example.

Tips for retrieving or recognizing different requests in an asynchronous queue request
A. You can set a context (userinfo) to the request object. After the request response is complete, you can access the userinfo of the request object to obtain the information in it.
B. set different setdidfinishselector/setdidfailselector callback methods for each request instance.
C. Subclass asihttprequest, rewrite requestfinished: And failwithproblem: Method

Asinetworkqueues, whose delegate provides richer Functions
More callback methods are provided as follows:
A, 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.
B, requestdidreceiveresponseheadersselector. After receiving the response header, design this method.DownloadBig Data is quite useful. You can do more business processing in the method.
C, requestdidfinishselector. This method is called when the request and response are successful.
D, requestdidfailselector, request failed
E, 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.

Reference text \ ">
By default, if a request in the queue fails, it will cancel all unfinished requests. You can set [queue setshouldcancelallrequestsonfailure: No] to correct the problem.

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 requests that reference cancellation are processed based on request failure and the call request fails to be 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:

Copy code

  1. -(Void) dealloc
  2. {
  3. [Request cleardelegatesandcancel];
  4. [Request release];
  5. ...
  6. [Super dealloc];
  7. }

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

Copy code

  1. Asiformdatarequest * request = [asiformdatarequest requestwithurl: url];
  2. [Request setpostvalue: @ "Ben" forkey: @ "first_name"];
  3. [Request setpostvalue: @ "copsey" forkey: @ "last_name"];
  4. [Request setfile: @ "/users/BEN/desktop/ben.jpg" forkey: @ "photo"];
  5. [Request adddata: imagedata withfilename: @ "george.jpg" andcontenttype: @ "image/JPEG" forkey: @ "Photos"];

To send custom data:

Copy code

  1. Asihttprequest * request = [asihttprequest requestwithurl: url];
  2. [Request appendpostdata: [@ "this is my data" datausingencoding: nsutf8stringencoding];
  3. // Default becomes post when you use appendpostdata:/appendpostdatafromfile:/setpostbody:
  4. [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:
1. If the data is compressed, decompress the package and put the file in the downloaddestinationpath directory. The temporary file is deleted.
2. If the download fails, the temporary file is directly moved to the downloaddestinationpath directory and replaced with the file of the same name.

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

Copy code

  1. [Request responsestatuscode];
  2. [[Request responseheaders] objectforkey: @ "X-powered-by"];
  3. [Request responseencoding];

GET request progress
There are two callback methods to get the request progress,
1. downloadprogressdelegate to get the download progress
2. 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:

Copy code

  1. // Create a cookie
  2. Nsdictionary * properties = [[nsmutabledictionary alloc] init] autorelease];
  3. [Properties setvalue: [@ "test value" encodedcookievalue] forkey: nshttpcookievalue];
  4. [Properties setvalue: @ "asihttprequesttestcookie" forkey: nshttpcookiename];
  5. [Properties setvalue: @ ".allseeing-i.com" forkey: nshttpcookiedomain];
  6. [Properties setvalue: [nsdate datewithtimeintervalsincenow: 60*60] forkey: nshttpcookieexpires];
  7. [Properties setvalue: @ "/ASI-http-Request/tests" forkey: nshttpcookiepath];
  8. Nshttpcookie * cookie = [[nshttpcookie alloc] initwithproperties: properties] autorelease];
  9. // This URL will return the value of the 'asihttprequesttestcookie 'cookie
  10. Url = [nsurl urlwithstring: @ "http://allseeing-i.com/ASIHTTPRequest/tests/read_cookie"];
  11. Request = [asihttprequest requestwithurl: url];
  12. [Request setusecookiepersistence: No];
  13. [Request setrequestcookies: [nsmutablearray arraywithobject: cookie];
  14. [Request startsynchronous];
  15. // Shocould be: I have 'test value' as the value of 'asihttprequesttestcookie'
  16. Nslog (@ "% @", [Request responsestring]);

Resumable upload of large files
0.94 and later support resumable download of large files, you only need to set:
[Request setallowresumeforfiledownloads: Yes];
[Request setdownloaddestinationpath: downloadpath];
You can.

Copyright belongs to trademanager ~ Reprinted with a reputation ~

From: http://wiki.magiche.net/pages/viewpage.action? Pageid = 2064410

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.