"Go" iOS Learning Note (eight)--ios network communication HTTP Nsurlconnection

Source: Internet
Author: User

In the era of mobile internet, network communication is an essential function of mobile terminal. The use of network communication is also essential in our applications to enhance client-server interaction. This article provides a way to implement HTTP communication using Nsurlconnection.

Nsurlconnection provides two ways of communicating asynchronous requests and synchronous requests.

1. Asynchronous request

The new SendAsynchronousRequest:queue:completionHandler: Method in the iOS5.0 SDK Nsurlconnection class enables the iOS5 to support two asynchronous request methods. Let's start with the new class.

1) sendasynchronousrequest

IOS5.0 begins to support the Sendasynchronousreques method, using the following method:

[CPP]View Plaincopyprint?
  1. -(void) httpasynchronousrequest{
  2. Nsurl *url = [Nsurl urlwithstring:@"Http://url"];
  3. NSString *[email protected]"PostData";
  4. NSData *postdata = [post datausingencoding:nsasciistringencoding allowlossyconversion:yes];
  5. Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];
  6. [Request sethttpmethod:@"POST"];
  7. [Request Sethttpbody:postdata];
  8. [Request settimeoutinterval:10.0];
  9. Nsoperationqueue *queue = [[Nsoperationqueue alloc]init];
  10. [Nsurlconnection Sendasynchronousrequest:request
  11. Queue:queue
  12. completionhandler:^ (Nsurlresponse *response, NSData *data, Nserror *error) {
  13. if (error) {
  14. NSLog (@"httperror:%@%d", Error.localizeddescription,error.code);
  15. }else{
  16. Nsinteger responsecode = [(Nshttpurlresponse *) response StatusCode];
  17. NSString *responsestring = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];
  18. NSLog (@"httpresponsecode:%d", responsecode);
  19. NSLog (@"Httpresponsebody%@", responsestring);
  20. }
  21. }];
  22. }


Sendasynchronousreques can easily use Nsurlrequest to receive callbacks to complete HTTP communication.

2) Connectionwithrequest

IOS2.0 began to support the Connectionwithrequest method, using the following:

[CPP]View Plaincopyprint?
  1. -(void) httpconnectionwithrequest{
  2. NSString *urlpath = [NSString stringwithformat:@"Http://url"];
  3. Nsurl *url = [Nsurl Urlwithstring:urlpath];
  4. Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];
  5. [Nsurlconnection connectionwithrequest:request delegate:self];
  6. }
  7. -(void) connection: (Nsurlconnection *) theconnection didreceiveresponse: (nsurlresponse *) Response
  8. {
  9. Nsinteger responsecode = [(Nshttpurlresponse *) response StatusCode];
  10. NSLog (@"response length=%lld statecode%d", [response Expectedcontentlength],responsecode);
  11. }
  12. A delegate method called by the Nsurlconnection as data arrives. The
  13. Response data for a POST was only for useful for debugging purposes,
  14. So we just drop it on the floor.
  15. -(void) connection: (Nsurlconnection *) theconnection didreceivedata: (NSData *) Data
  16. {
  17. if (mdata = = nil) {
  18. Mdata = [[Nsmutabledata alloc] initwithdata:data];
  19. } Else {
  20. [Mdata Appenddata:data];
  21. }
  22. NSLog (@"response connection");
  23. }
  24. A delegate method called by the nsurlconnection if the connection fails.
  25. We shut down the connection and display the failure. Production Quality Code
  26. Would either display or log the actual error.
  27. -(void) connection: (Nsurlconnection *) theconnection didfailwitherror: (nserror *) Error
  28. {
  29. NSLog (@"Response error%@", [Error Localizedfailurereason]);
  30. }
  31. A delegate method called by the nsurlconnection when the connection have been
  32. Done successfully. We shut down the connection with a nil status, which
  33. Causes the image to be displayed.
  34. -(void) connectiondidfinishloading: (nsurlconnection *) theconnection
  35. {
  36. NSString *responsestring = [[NSString alloc] Initwithdata:mdata encoding:nsutf8stringencoding];
  37. NSLog (@"Response body%@", responsestring);
  38. }

Connectionwithrequest need delegate parameters, through a delegate to do the data download and request acceptance and connection status, here Delegate:self, so need to implement some methods of this class, Also define mdata to do the acceptance of the data.

Methods that need to be implemented:

1, get the return status, Baotou information.

[CPP]View Plaincopyprint?
    1. -(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response;


2, connection failure, including failure.

[CPP]View Plaincopyprint?
    1. -(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error;

3. Receive data

[CPP]View Plaincopyprint?
    1. -(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data;

4. Data reception Complete

-(void) connectiondidfinishloading: (nsurlconnection *) connection;

Connectionwithrequest is more cumbersome to use, and iOS5.0 is not supported sendasynchronousrequest. A netizen has put forward aeurlconnection solution.

[HTML]View Plaincopyprint?
    1. Aeurlconnection is a simple reimplementation of the API for use on IOS 4. Used properly, it's also guaranteed to being safe against the deallocation problem, a thorny threading issue that affects Mo St Other networking libraries.

2. Synchronous request

The synchronous request data method is as follows:

[CPP]View Plaincopyprint?
  1. -(void) httpsynchronousrequest{
  2. Nsurlrequest * URLRequest = [nsurlrequest requestwithurl:[nsurl urlwithstring:@"http://google.com"]];
  3. Nsurlresponse * response = nil;
  4. Nserror * error = NIL;
  5. NSData * data = [Nsurlconnection sendsynchronousrequest:urlrequest
  6. Returningresponse:&response
  7. error:&error];
  8. if (Error = = nil)
  9. {
  10. //Processing data
  11. }
  12. }



Synchronizing request data can cause the main thread to block, and it is often not recommended when big data is requested or the network is not smooth.

As you can see from the code above, the steps to establish communication are basically the same regardless of the synchronous request or the asynchronous request:

1. Create Nsurl

2. Create a Request object

3. Create a nsurlconnection connection.

Once the nsurlconnection is created, an HTTP connection is created. The difference between an asynchronous request and a synchronous request is that an asynchronous request is created, the user can do other things, the request is executed on another thread, and the communication results and procedures are executed in the callback function. Synchronization requests are different and require the end user to be requested to do other things.

/*** @author Zhang Xingye * http://blog.csdn.net/xyz_lmn* iOS starter Group: 83702688* Android Development Advanced Group: 241395671* my Sina Weibo:@ Zhang Xingye tbow* * Reference: http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/urlloadingsystem/tasks/ usingnsurlconnection.html#//apple_ref/doc/uid/20001836-bajeaieehttp://codewithchris.com/ tutorial-how-to-use-ios-nsurlconnection-by-example/http://kelp.phate.org/2011/06/ Ios-stringwithcontentsofurlnsurlconnect.html from:http://blog.csdn.net/xyz_lmn/article/details/8968182

"Go" iOS Learning Note (eight)--ios network communication HTTP Nsurlconnection

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.