IOS learning-network basics, ios-network Basics

Source: Internet
Author: User

IOS learning-network basics, ios-network Basics

Get & Post request

• Four Steps for Network Access

-Address-request-connection-processing result • common classes for iOS network processing-NSURL (Address)-NSRequest [GET] & NSMutableURLRequest [POST] (request)-NSConnection (connection) • Implementing the NSURLConnectionDataDelegate proxy method can receive Server Response Data (processing results) about the proxy method: • problems with the proxy method-many proxy methods are scattered-one request needs to be processed, code needs to be written in many places-not conducive to logic implementation, code writing, debugging, maintenance, and expansion-especially when there are multiple requests it will become very troublesome! • Learned proxy methods-UIApplicationDelegate-UITableViewDelegate, UITableViewDataSource-UITextFieldDelegate-custom proxy methods through protocols-NSURLConnectionDataDelegate synchronous and asynchronous requests: • NSURLConnection provides two static methods that can call NSURLRequest directly or asynchronously without obtaining data through NSURLConnectionDataDelegate • synchronous request:

SendSynchronousRequest: request returningResponse: & response error: & error

• Asynchronous request:

SendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * error)

Content about the main operation queue is described in the multi-thread Course

Cache Policy: you can set a cache policy for the cachePolicy attribute of NSURLRequest, which is a memory cache, non-hard disk cache • The purpose of using the cache is to make the application respond to user input more quickly and make the program run efficiently. Sometimes we need to cache the data obtained by remote web servers to reduce the number of requests to the same url for multiple times. • cachePolicy supports the following cache policies:-NSURLRequestUseProtocolCachePolicy default cache policies, you must specify the cache logic in the implementation method of the Protocol-NSURLRequestReloadIgnoringCacheData ignoring the download of the cache from the original address-NSURLRequestReturnCacheDataElseLoad downloading from the original address-using the cache only, this method is applicable to the offline mode where no network connection is established-the local and remote cache data is ignored and directly downloaded from the original address. It is similar to NSURLRequestReloadIgnoringCacheData-NSURLRequestReloadRevalidatingCacheData to verify whether the local data and, if different, the remote data is downloaded. Otherwise, the local data is used.

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.

(Today I learned about the basics of the network. The code is repetitive and the cache policy has not been learned yet)

The following is the get and post code:

# Pragma mark-test get method-(IBAction) getLogin :( UIButton *) btn {static NSString * loginUrl = @ "http: // 192.168.1.102: 8080/IOSApplication/LoginServletController. do "; // initialize data _ receiveDate = [NSMutableData data]; // defines the URL NSString * urlStr = [NSString stringWithFormat: @" % @? Username = % @ & password = % @ ", loginUrl, _ userName. text, _ password. text]; // note: the URL of the network request must be encoded before it can be used !!! _ NSURL * url = [NSURL URLWithString: urlStr]; // defines the request NSURLRequest * request = [NSURLRequest requestWithURL: url]; // define the connection NSURLConnection * cont = [[NSURLConnection alloc] initWithRequest: request delegate: self]; [cont start];} # pragma mark-network connection error determination-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error {NSLog (@ "network connection error % @", error. localizedDescription) ;}# pragma mark-receive response-(void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response {NSLog (@ "start receiving response ");} # pragma mark-received data-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {NSLog (@ "received data from the server: % @", data ); [_ receiveDate appendData: data] ;}# pragma mark-connection end-(void) connectionDidFinishLoading :( NSURLConnection *) connection {NSString * backString = [[NSString alloc] initWithData: _ receiveDate encoding: NSUTF8StringEncoding]; NSLog (@ "end received data % @", backString); _ receiveDate = nil;} # pragma mark-test post method-(IBAction) postLogin :( UIButton *) btn {static NSString * loginUrl = @ "http: // 192.168.1.102: 8080/IOSApplication/LoginServletController. do "; // initialize data _ receiveDate = [NSMutableData data]; // you do not need to encode NSURL * URL = [NSURL URLWithString: loginUrl] for URLs consisting of letters and numbers. // define the request NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; // wait for the response time of the Server 5 [request setTimeoutInterval: 5.0]; // set the request method [request setHTTPMethod: @ "post"]; NSString * bodyString = [NSString stringWithFormat: @ "username =%@ & password =%@", _ userName. text, _ password. text]; // generate the request data and encode NSData * body = [bodyString dataUsingEncoding: NSUTF8StringEncoding]; // set the HTTP request data body, NSMutableURLRequest will automatically add Content-Length [request setHTTPBody: body] to the request Header; // set NSURLConnection * cont = [[NSURLConnection alloc] initWithRequest: request delegate: self]; // start connection [cont start];} # pragma mark-send data to the server. This method is used for POST requests-(void) connection :( NSURLConnection *) connection didSendBodyData :( NSInteger) bytesWritten transaction :( NSInteger) totalBytesWritten transaction :( NSInteger) Transaction {NSLog (@ "send data to server bytesWritten: % ld, totalBytesWritten % ld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite );}

 

The following are synchronous and asynchronous (NSURLConnection provides two static methods to call NSURLRequest directly or asynchronously without obtaining data through NSURLConnectionDataDelegate)

// Generate post request-(NSMutableURLRequest *) postLoginRequest {static NSString * loginUrl = @ "http: // 192.168.1.102: 8080/IOSApplication/LoginServletController. do "; // initialize data _ receiveDate = [NSMutableData data]; // you do not need to encode NSURL * URL = [NSURL URLWithString: loginUrl] for URLs consisting of letters and numbers. // define the request NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; // wait for the response time of the Server 5 [request setTimeoutInterval: 5.0]; // configure Method [request setHTTPMethod: @ "post"]; NSString * bodyString = [NSString stringWithFormat: @ "username =%@ & password =%@", _ userName. text, _ password. text]; // generate the request data and encode NSData * body = [bodyString dataUsingEncoding: NSUTF8StringEncoding]; // set the HTTP request data body, NSMutableURLRequest will automatically add Content-Length [request setHTTPBody: body]; return request;} # pragma mark-post synchronous login-(IBAction) synchronizationLogin :( UIButton *) B to the request Header Tn {NSMutableURLRequest * request = [self postLoginRequest]; NSError * error; NSURLResponse * response; NSDate * date = [NSURLConnection sendSynchronousRequest: request returningResponse: & response error: & error]; // note that subsequent operations are performed only after the synchronization request is completed. You can see the effect if (! Date) {NSLog (@ "synchronization access error: % @", error. localizedDescription);} else {// decodes data NSString * string = [[NSString alloc] initWithData: date encoding: NSUTF8StringEncoding]; NSLog (@ "synchronize data % @", string) ;}# pragma mark-post asynchronous login-(IBAction) asynchronizationLogin :( UIButton *) btn {NSMutableURLRequest * request = [self postLoginRequest]; // note that block code is used here! The asynchronous request queue uses the main queue column [NSURLConnection sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {if ([data length]> 0 & connectionError = nil) {NSString * string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@ "data returned asynchronously" % @ ", string);} else if ([data length] <= 0 & connectionError = nil) {NSLog (@ "No returned data received");} else {NSLog (@ "Asynchronous Access Error % @", connectionError. localizedDescription) ;}}] ;}

 

 

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.