IOS ----- use NSURLConnection and nsurlconnection

Source: Internet
Author: User

IOS ----- use NSURLConnection and nsurlconnection
Use NSURLConnection

To read server data such as HTTP or submit data to the server, iOS also provides the NSURLConnection class. NSURLConnection uses NSURLRequest to send synchronous or asynchronous requests to the remote server, and obtain the server response data. In addition to NSURLRequest, you can also use NSMutableURLRequest to send data to the server.

Use NSURLConnection to obtain data from the network

NSURLConnection can be used to load server responses based on URLs. There are not many methods for this object. If this object is used to asynchronously load server responses, you need to specify an object that complies with the NSURLConnectionDelegate protocol for this object, as the delegate of NSURLConnection, this object is responsible for handling events during asynchronous loading.

In addition, the sendSynchronousRequest: returningResponse: error: Class Method of NSURLConnection can be used to synchronize the server response on the shelf.

NSURLConnection provides the following common methods.

 

-(NSURLRequest *) originalRequest: gets the deep copy of The NSURLRequest object of the NSURLConnection.

-(NSURLRequest *) currentRequest: returns the NSURLRequest object currently used by the NSURLConnection.

You can use synchronous requests to obtain network data as follows:

+ SendSynchronousRequest: returningResponse: error: the second parameter represents the NSURLRequest object sending the request. The second parameter must be a pointer to the NSURLRequest object to obtain the server response object; the 3rd parameters are used to save the obtained error information.

The method for obtaining network data using asynchronous requests is as follows:

+ ConnectionWithRequest: delegate: use an asynchronous request to obtain data. The 2nd parameters are used as the NSURLConnection delegate.

-InitWithRequest: delegate: This method is basically the same as the previous method, but this method is an instance method. You must call alloc before calling this method.

-InitWithRequest: delegate: startImmediately: similar to the functions of the previous method, only the startImmediately parameter is added, which controls whether to send requests immediately.

+ SendAsynchronousRequest: queue: completionHandler: This method requires an additional NSOperationQueue parameter, indicating that the request is sent to the specified NSOperationQueue for processing.

-Start: start sending the request. Only when the request is sent through-initWithRequest: delegate: startImmediately: Method to send the request, and the last parameter isNOTo call this method.

UseNSURLConnectionTo obtain data from a network, follow these steps:

1.CreateNSURLRequestObject, which represents the request to the remote server. This object can include the requestedURLCache Policy, timeout length, and other information.

2.CallNSURLConnectionToNSURLRequestObject for parameter CreationNSURLConnectionYou can send a request.

3.If the call method loads the server response asynchronouslyNSURLConnectionObject specifiedDelegateObject, so you also needDelegeteObject implementation specific method.

Code snippet

ViewController. m @ implementation ViewControllerNSMUtableData * totalData;-(void) viewDidLoad {[super viewDidLoad]; NSString * str = @ http://www.crazyit.ory/ethos.php; totalData = [[NSMutableData alloc] init]; // create NSURL object NSURL * url = [NSURL URLWithString: str] with specified NSString; // create NSURLRequest object // NSURLRequest * request = [NSURLRequest requestWithURL: url]; // NSURLRequest created in this way can specify the Cache Policy and timeout duration NSURLRequest * Request = [NSURLRequest requestWithURL: urlcachePolicy: Required timeoutInterval: 5]; // create a connection with the specified URL and delegate, and send the request NSURLConnection * conn = [NSURLConnection connectionWithRequest: request delegate: self]; // if conn is nil, if (conn! = Nil) {return ;}}// this method is triggered when the server response is generated-(void) connection: (NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response {NSLog (@ "+ + didReceiveResponse ++"); NSLog (@ "response data type: % @", response. MIMEType); // obtain the response Data Length. If the length cannot be detected, NSURLResponseUnknownLength (-1) NSLog (@ "the response data length is % lld", response. expectedContentLength); NSLog (@ "character set used by the response data: % @", response. textEncodingName); NSLog (@ "response file name: % @", response. suggestedFilename);} // This method is triggered every time the server reads the response data. // For a request, server data may have to be read several times, therefore, this method will be penalized multiple times. // if the program needs to convert the data into a string, we recommend that you use NSMutableData to collect the data. then the overall conversion-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {[totalData appendData: data];} // This method is triggered when an error occurs on the connection server. you can get the error message through error-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error {NSLog (@ "++ error ++ ");} // This method is triggered when data load is complete. for each request, this method is only triggered once-(void) connectionDidFinishLoading :( NSURLConnection *) connection {NSLog (@ "++ finishLoading ++ "); NSString * content = [[NSString alloc] initWithData: totalDataencoding: NSUTF8StringEncoding]; // clear all data [totalData setLength: 0]; self. showView. text = content;} @ end

 

The1The line of red code createsNSURLRequestObject2Line of red codeNSURLRequestThe view controller is used as the parameter.Delegate, CreatedNSURLConnectionObject To send requests to the remote server.

Because the program uses the View Controller itselfNSURLConnectionOfDelegateTherefore, the View Controller implementsNSURLConnectionDataDelegateProtocol and implement several specific methods in the Protocol.

With the arrival of server response,NSURLConnectionOfDelegateThe following methods of objects are called in sequence:

1.Connection: didReceiveResponse:When the server responds,Stimulate this method

2.Connection: didReceiveData:Each time you read the server response data,Will stimulate this method.For a request,The server data may have to be read several times.,Therefore, this method will be triggered multiple times..

3.ConnectionDidFinishLoading:This method is triggered when the server responds to read completion..

 
 

 

 

Use NSMutableURLRequest to send data to the server

NSMutableURLRequest can not only add request headers, but also add request parameters to send data to the server.

The following common methods are added for NSMutableURLRequest:

-AddValue: forHTTPHeaderField: This method is used to add a request header for NSMutableURLRequest.

-SetAllHTTPHeaderFields: This method uses an NSDictionary to set multiple request headers for NSMutableURLRequest at a time.

-SetHTTPBody: Set NSMutableURLRequest Request body data ----- That is, Set Request Parameters

-SetHTTPBodyStream: sets the Request body data of NSMutableURLRequest with NSInputStream as the parameter. This method and setHTTPBody method can only be set to one

-SetHTTPMethod: Set the request submission method, either POST or GET. The default value is GET.

-SetHTTPShouldHandleCookies: sets whether the HTTP request processes cookies.

-SetValue: forHTTPHeaderField: sets the request value for the specified request header.

Sample Code

1 ViewController. m 2 3 @ implementation ViewController 4 5 NSMutableData * totalData; 6 7-(void) viewDidLoad 8 9 {10 11 [super viewDidLoad]; 12 13 NSString * str = @ "http: // 192.168.1.88.8888/abc/login. jsp "; 14 15 totalData = [[NSMutableData alloc] init]; 16 17 // create an NSURL object 18 19 NSURL * url = [NSURL URLWithString: str] with the specified NSString; 20 21 // create NSURLRequest object 22 23 // NSURLRequest * request = [NSURLReques T requestWithURL: url]; 24 25 // NSURLRequest created in this way can specify the Cache Policy and timeout length 26 27 NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url 28 29 cachePolicy: listen 30 31 timeoutInterval: 5]; 32 33 // -------------------- the following code starts to set the request parameter ------------------ 34 35 // prepare the request parameter 36 37 NSString * post = [NSString stringWithFormat: @ "name =%@ & pass =%@", @ "crazyit.org", @ "crazy software "]; 38 39 // convert the request parameter to NSData 40 41 NSData * postData = [post dataUsingEncoding: NSUTF8StringEncoding]; 42 43 NSString * postLength = [NSString stringWithFormat: @ "% d", [postData length]; 44 45 // sets the request method. By default, the GET request is sent 46 47 [request setHTTPMethod: @ "POST"]; 48 49 // Add two request headers 50 51 [request setValue: postLength forHTTPHeaderField: @ "Content-Length"]; 52 53 [request setValue: @ "application/x-www-form-urlencoded" 54 55 forHTTPHeaderField: @ "Content-Type"]; 56 57 // set the request data to HTTP request body 58 59 [request setHTTPBody: postData]; 60 61 // create a connection with the specified URL and delegate and send a request 62 63 NSURLConnection * conn = [NSURLConnection connectionWithRequest: request 64 65 delegate: self]; 66 67 // if conn is nil, 68 69 if (conn! = Nil) 70 71 {72 73 return; 74 75} 76 77} 78 79 // This method is triggered when the server response is generated 80 81-(void) connection: (NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response 82 83 {84 85 NSLog (@ "+ + didReceiveResponse ++"); 86 87 NSLog (@ "response data type: % @", response. MIMEType); 88 89 // obtain the Response Data Length. If the length cannot be detected, the NSURLResponseUnknownLength (-1) 90 91 NSLog (@) is returned. The response data length is: % lld ", response. expectedContentLength); 92 93 NSLog (@ "the character set used by the response data: % @", response. textEncodingName); 94 95 NSLog (@ "response file name: % @", response. suggestedFilename); 96 97} 98 99 // The method 100 101 is triggered each time the server reads the response data. // For a request, server data may have to be read several times, so this method will be penalized for multiple times 102 103 // if the program needs to convert the data into strings, we recommend that you use NSMutableData to collect the data. then the overall conversion is 104 105-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data106 107 {108 109 [totalData appendData: data]; 110 111} 112 113 // This method is triggered when an error occurs during connection to the server. error 114 115-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error116 117 {118 119 NSLog (@ "+ + error ++ "); 120 121} 122 123 // This method is triggered when data load is complete. for each request, this method will only be triggered once 124 125-(void) connectionDidFinishLoading :( NSURLConnection *) connection126 127 {128 129 NSLog (@ "++ finishLoading ++ "); 130 131 NSString * content = [[NSString alloc] initWithData: totalData132 133 encoding: NSUTF8StringEncoding]; 134 135 136 // clear all data 137 138 [totalData setLength: 0]; 139 self. showView. text = content; 140 141} 142 143 @ end

 

The key of the above Code is the red code, which sets to send a POST request, and convert a string like "name = crazyit.org & pass = crazy software" into NSData as the request parameter, and set the value of two request headers according to the Request Parameters ----- in this way, a NSMutableURLRequest with the request parameters is obtained.

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.