"OBJECTIVE-C" HTTP common API, synchronous request and asynchronous request [go]

Source: Internet
Author: User
Tags vars

More practical, reproduced save

Developing iOS apps to invoke HTTP interfaces, get HTTP resources, have a fairly mature framework asihttprequest. I prefer to use the original API, which has many similarities with other object-oriented languages. This article describes the use of HTTP APIs in both synchronous and asynchronous requests. Directly on the code, the note is the document!

Synchronous Request : initiates an HTTP request, gets and processes the return value in the same thread

[OBJC]View Plaincopy
  1. Create a URL object
  2. NSString *urlstr = @ "Http://blog.csdn.net/rongxinhua";
  3. Nsurl *url = [[Nsurl alloc] initwithstring:urlstr];
  4. Create an HTTP request
  5. Method 1 (Note: Nsurlrequest only supports get requests, nsmutableurlrequest can support get and post requests)
  6. Nsurlrequest *request = [[Nsurlrequest alloc] Initwithurl:url];
  7. Nsmutableurlrequest *request = [[Nsmutableurlrequest alloc] Initwithurl:url];
  8. Method 2, use the factory method to create
  9. Nsurlrequest *request = [nsurlrequest requestwithurl:url];
  10. Nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url];
  11. Set cache policy and timeout time
  12. Nsmutableurlrequest *request = [nsurlrequest requestwithurl:url cachepolicy:  Nsurlrequestreloadignoringlocalcachedata timeoutinterval:15];
  13. Set HTTP Headers
  14. Nsdictionary *headers = [request Allhttpheaderfields];
  15. [Headers setValue:@ "IOS-CLIENT-ABC" Forkey:@ "User-agent"];
  16. Set Request method
  17. [Request Sethttpmethod:@ "GET"];
  18. [Request Sethttpmethod:@ "POST"];
  19. Set the body content to be sent (for post requests)
  20. NSString *content = @ "username=stanyung&password=123";
  21. NSData *data = [content datausingencoding:nsutf8StringEncoding];
  22. [Request Sethttpbody:data];
  23. Synchronously executes an HTTP request to get the returned data
  24. Nsurlresponse *response;
  25. Nserror *error;
  26. NSData *result = [nsurlconnection sendsynchronousrequest:request returningresponse:&response Error:  &error];
  27. Return data into a string
  28. NSString *html = [[NSString alloc] initwithdata:result encoding:nsutf8StringEncoding];
  29. Error description (if there is an error)
  30. NSString *errordesc = [error localizeddescription];
  31. Get status code and HTTP response header information
  32. Nshttpurlresponse *httpresponse = (nshttpurlresponse *) response;
  33. Nsinteger StatusCode = [HttpResponse statusCode];
  34. Nsdictionary *responseheaders = [HttpResponse allheaderfields];
  35. NSString *cookie = [responseheaders valueforkey:@ "Set-cookie"];

Note: The above code, do not copy directly, just enumerate the HTTP common methods of invocation.

Asynchronous Request : initiates an HTTP request in one thread, returning the result to be processed in another thread. The asynchronous request does not need to wait for the result to be returned, and the current program can continue to execute as compared to the synchronization request. In Objective-c, asynchronous requests also have two implementations: one is to register a callback proxy and one is to use a callback code block.

A. How to register a callback agent:

[OBJC]View Plaincopy
    1. [Nsurlconnection connectionwithrequest:request delegate: Self];

Need to implement the Nsurlconnectiondatadelegate protocol:

[OBJC]View Plaincopy
    1. @interface httpdownloadservice:nsobject<nsurlconnectiondatadelegate> {
    2. }

Implement the relevant protocol method:

[OBJC]View Plaincopy
  1. Nsmutabledata *buff; //Staging response data
  2. BOOL finished = false; //Finish reading full Mark
  3. Called when an HTTP response is received
  4. -(void) connection: (nsurlconnection *) connection didreceiveresponse: (nsurlresponse *) Response {
  5. nshttpurlresponse *httpresponse = (nshttpurlresponse*) response;
  6. nsdictionary *headers = [HttpResponse allheaderfields];
  7. Buff = [[Nsmutabledata alloc] init];
  8. }
  9. Called when the return data is read (this method may be executed more than once)
  10. -(void) connection: (nsurlconnection *) connection didreceivedata: (nsdata *) data {
  11. [Buff appenddata:data];
  12. }
  13. Called when the data is finished reading
  14. -(void) connectiondidfinishloading: (nsurlconnection *) connection {
  15. nsstring *html = [[NSString alloc] initwithdata:buff encoding:nsutf8StringEncoding];
  16. Finished = true;
  17. }

Typically, data is transmitted over the network and is affected by factors such as bandwidth, and does not return all data at once, and you may be able to accept a complete HTTP response message several times. Therefore, (void) connection: (Nsurlconnection *) Didreceivedata: (NSData *) This method is likely to be executed several times.

In the example code, the Nsmutabledata is used to stage the received response data fragments, and each segment is then connected until the read is complete.

B. How to use the callback code block:

[OBJC]View Plaincopy
  1. [Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] Completionhandler:
  2. ^ (nsurlresponse *response, nsdata *result, nserror *error) { //will only enter once, the method has already implemented the buffer function inside
  3. nsstring *html = [[NSString alloc] initwithdata:result encoding:nsutf8StringEncoding];
  4. }];

Unlike the Nsurlconnectiondatadelegate callback method, where the callback code block is called only once, it has already implemented the function of buffer inside, until the data is received intact before entering this block of code. Therefore, the result that you get in the code block can be used directly.

Note 1: The code example in this article will use the ARC encoding mode, so the newly created object does not explicitly call the release () method for recycling.

NOTE 2: If you test this example code new command line tool project, in the main function to execute the relevant code, the above two asynchronous execution situation, you most likely your program did not execute to the callback method or callback code block inside, because: in the main function, The main thread does not wait for blocking, all of a sudden, the callback code is in the child thread may not be executed or have not started execution, it has been due to the end of the main thread. To solve this problem, the code can be followed after the asynchronous method is called:

[OBJC]View Plaincopy
    1. while (!finished) {
    2. [[Nsrunloop Currentrunloop] runmode:nsdefaultrunloopmode beforedate:[nsdate Distantfuture]];
    3. }

The finished variable is exactly what is defined in the above two asynchronous HTTP examples to perform the completion.

@ Capacity Xinhua Technology Blog-Http://blog.csdn.net/rongxinhua-original articles, reproduced please specify the source

"OBJECTIVE-C" HTTP common API, synchronous request and asynchronous request [go]

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.