IOS study notes (8)-Ios network communication http-nsurlconnection

Source: Internet
Author: User

In the mobile Internet era, network communication is essential for mobile terminals. Network communication is also essential for our applications to enhance client-to-server interaction. This article provides the method of using NSURLConnection to implement http Communication.

NSURLConnection provides two communication modes: asynchronous request and synchronous request.

1. asynchronous requests

The sendAsynchronousRequest: queue: completionHandler: method added to the iOS5.0 SDK NSURLConnection class enables iOS5 to support two asynchronous request methods. Let's start with adding a class.

1) sendAsynchronousRequest

IOS5.0 starts to support the sendAsynchronousReques method. The method is as follows:

- (void)httpAsynchronousRequest{    NSURL *url = [NSURL URLWithString:@"http://url"];        NSString *post=@"postData";        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    [request setHTTPMethod:@"POST"];    [request setHTTPBody:postData];    [request setTimeoutInterval:10.0];        NSOperationQueue *queue = [[NSOperationQueue alloc]init];    [NSURLConnection sendAsynchronousRequest:request                                       queue:queue                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){                               if (error) {                                   NSLog(@"Httperror:%@%d", error.localizedDescription,error.code);                               }else{                                                                      NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];                                                                      NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];                                                                      NSLog(@"HttpResponseCode:%d", responseCode);                                   NSLog(@"HttpResponseBody %@",responseString);                               }                           }];    }

SendAsynchronousReques can easily use NSURLRequest to receive callbacks and complete http Communication.
2) connectionWithRequest

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

- (void)httpConnectionWithRequest{        NSString *URLPath = [NSString stringWithFormat:@"http://url"];    NSURL *URL = [NSURL URLWithString:URLPath];    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];    [NSURLConnection connectionWithRequest:request delegate:self];    }- (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response{       NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];    NSLog(@"response length=%lld  statecode%d", [response expectedContentLength],responseCode);}// A delegate method called by the NSURLConnection as data arrives.  The// response data for a POST is only for useful for debugging purposes,// so we just drop it on the floor.- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data{    if (mData == nil) {        mData = [[NSMutableData alloc] initWithData:data];    } else {        [mData appendData:data];    }    NSLog(@"response connection");}// A delegate method called by the NSURLConnection if the connection fails.// We shut down the connection and display the failure.  Production quality code// would either display or log the actual error.- (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error{        NSLog(@"response error%@", [error localizedFailureReason]);}// A delegate method called by the NSURLConnection when the connection has been// done successfully.  We shut down the connection with a nil status, which// causes the image to be displayed.- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection{    NSString *responseString = [[NSString alloc] initWithData:mData encoding:NSUTF8StringEncoding];     NSLog(@"response body%@", responseString);}

ConnectionWithRequest requires the delegate parameter to download data and Request acceptance and connection status using a delegate statement. Here, delegate: self is required, and define mData for data acceptance.

Implementation Method:


1. Obtain the returned status and header information.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

2. Connection Failed, including failure.

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;


3. receive data

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;


4. Data reception is complete

-(Void) connectionDidFinishLoading :( NSURLConnection *) connection;

The use of connectionWithRequest is cumbersome, and the use of iOS5.0 does not support sendAsynchronousRequest. Some netizens have proposed the AEURLConnection solution.

AEURLConnection is a simple reimplementation of the API for use on iOS 4. Used properly, it is also guaranteed to be safe against The Deallocation Problem, a thorny threading issue that affects most other networking libraries.

2. synchronous request

The method for synchronizing request data is as follows:

-(Void) httpSynchronousRequest {NSURLRequest * urlRequest = [NSURLRequest requestWithURL: [NSURL URLWithString: @ "http://google.com"]; NSURLResponse * response = nil; NSError * error = nil; NSData * data = [NSURLConnection sendSynchronousRequest: urlRequest returningResponse: & response error: & error]; if (error = nil) {// process data }}

Synchronizing request data will cause the main thread to be blocked. It is generally not recommended when the request for big data or the network is poor.


From the code above, we can see that the steps for establishing communication are basically the same, regardless of synchronous or asynchronous requests:

1. Create an NSURL

2. Create a Request object

3. Create an NSURLConnection connection.

After NSURLConnection is created, an http connection is created. The difference between an asynchronous request and a synchronous request is that when an asynchronous request is created, you can perform other operations. The request is executed in another thread, and the communication result and process are executed in the callback function. Synchronous requests are different. You must end the request before performing other operations.

/**

* @ Author Zhang xingye * http://blog.csdn.net/xyz_lmn* iOS entry group: 83702688

* Android Development 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-BAJEAIEE
Http://codewithchris.com/tutorial-how-to-use-ios-nsurlconnection-by-example/
Http://kelp.phate.org/2011/06/ios-stringwithcontentsofurlnsurlconnect.html


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.