Summary of network requests 2. Summary of requests

Source: Internet
Author: User

Summary of network requests 2. Summary of requests

1 NSURLConnettion

NSURLConnettionIs an abstraction above the Core Foundation/CFNetwork framework API.NSURLConnettionIt refers to a series of components in the Foundation framework: NSURLRequest, NSURLResponse, NSURLProtocol, NSURLCache, NSHTTPCookieStorage, NSURLCredentialStorage, and NSURLConnection of the same name.

Note 1: original usage principle: An NSURLRequest is sent to NSURLConnect. The entrusted object (following the NSURLConnectionDeledate and NSURLConnectionDataDeledate informal protocols) asynchronously returns an NSURLResponce and the NSData of the server.

NOTE 2: When a request is sent to the server, the system first queries the cache information and then returns the response directly when the response is found in the cache based on the policy and available write. otherwise, the system caches the response after receiving the request according to our policy and returns it.

NOTE 3: When a request is sent to the server, the server will issue an authentication query, which can have shared cookies or confidential storage for automatic response, or be responded by the entrusted object. requests in the process of sending can also be intercepted by NSURLProtocol to seamlessly change requests when necessary.

NSURLConnettionSteps:

1. Get a URL

2. Create a request through URL

3. UseNSURLConnettionSend request

2NSURLSession

Like NSURLConnection, NSURLSession includes not only NSURLSession with the same name, but also NSURLRequest and NSURLCache. At the same time, NSURLConnection is mapped to NSURLSession, callback, and NSURLSession.

Compared with NSURLConnection, the maximum change of NSURLSession can be configured for each cached session cache, cookie value, protocol, certificate policy, and even kaug programs to share this information. this ensures the independence between the program and the network framework. each NSURLSession has an NSURLSessionConfiguration for initialization. NSURLSessionConfiguration specifies the policy and the performance enhancement options on mobile devices.

Another feature of NSURLSession is session tasks, which are used to process uploads and downloads. The biggest difference with NSURLConnection is that all tasks share their NSURLSession creators.

Note: NSURLSessionTask Analysis

NSURLSessionTask is an abstract class that contains three subclasses: NSURLSessionDataTask, NSURLSessionDownLoadTask, and NSURLSessionUpLoadTask. These three subclasses encapsulate basic network tasks: getting data, uploading and downloading.

 

Usage principle: When an NSURLSessionDataTask is completed, a returned data will be generated. When an NSURLSessionDownLoadTask is completed, a temporary file path will be included. A certain amount of data is returned during file upload. Therefore, NSURLSessionUpLoadTask inherits from NSURLSessionDataTask. all tasks can be canceled, paused, and resumed. When paused, the current position is logged back for download to continue. note that NSURLSessionTask is created by NSURLSession.

NSURLSessionThe procedure is similar to NSURLConnection, and then run it using the resume method.

1. Get a URL

2. Create a request through URL

2.1 create an uploaded NSData (used during UpLoad)

3. CreateNSURLSessionSingleton

4. PassNSURLSessionSend a request (Note: Use resume)

Instance:

1 DataTask

NSURL * URL = [NSURL URLWithString: @ "http://example.com"];

NSURLRequest * request = [NSURLRequest requestWithURL: URL];

 

NSURLSession * session = [NSURLSession sharedSession];

NSURLSessionDataTask * task = [session dataTaskWithRequest: request

CompletionHandler:

^ (NSData * data, NSURLResponse * response, NSError * error ){

//...

}];

 

[Task resume];

2 UpLoadTask

NSURL * URL = [NSURL URLWithString: @ "http://example.com/upload"];

NSURLRequest * request = [NSURLRequest requestWithURL: URL];

NSData * data = ...;

 

NSURLSession * session = [NSURLSession sharedSession];

NSURLSessionUploadTask * uploadTask = [session uploadTaskWithRequest: request

FromData: data

CompletionHandler:

^ (NSData * data, NSURLResponse * response, NSError * error ){

//...

}];

 

[UploadTask resume];

3 DownLoadTask

Note: The Download task also requires a request, which is different from the completionHandler block. Data task and upload task will return a one-time response when the task is completed, but Download task writes Data to a local temporary file a little bit. Therefore, in the completionHandler block, we need to move the file from a temporary address to a permanent address for storage.

NSURL * URL = [NSURL URLWithString: @ "http://example.com/file.zip"];

NSURLRequest * request = [NSURLRequest requestWithURL: URL];

 

NSURLSession * session = [NSURLSession sharedSession];

NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithRequest: request

CompletionHandler:

^ (NSURL * location, NSURLResponse * response, NSError * error ){

NSString * documentsPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

NSURL * documentsDirectoryURL = [NSURL fileURLWithPath: documentsPath];

NSURL * newFileLocation = [documentsDirectoryURL URLByAppendingPathComponent: [[response URL] lastPathComponent];

[[NSFileManager defaultManager] copyItemAtURL: location toURL: newFileLocation error: nil];

}];

 

[DownloadTask resume];

3. Differences between NSURLSession and NSURLConnection

NSURLSession has both session proxy methods and Task proxy methods. the session proxy method is used to handle connection layer issues (server Trust, client certificate evaluation, etc.), and the Task proxy method is used to handle authentication queries and problems related to network requests.

4 AFN framework

AFN is an encapsulation of NSURLConnection.

Main functions of AFN:

  • NSURLConnection

AFURLConnectionOperation

AFHTTPRequestOperation

AFHTTPRequestOperationManager (encapsulates common HTTP methods)

AFHTTPRequestOperationManager attributes

1. baseURL: The developer must customize a single example class for AFHTTPRequestOperationManager, set the baseURL, and only use the relative path for all network access.

2 requestSerializer: request data format/The default value is binary HTTP

3 responseSerializer: Response Data Format/JSON format by default

4 operationQueue

5 reachabilityManager: Network Connection Manager

AFHTTPRequestOperationManager method:

1 manager: easy to create manager class methods

2 HTTPRequestOperationWithRequest: when accessing the server, if you want to tell the server some additional information, you must set

3 GET

4 POST

  • NSURLSession

AFURLSessionManager

AFHTTPSessionManager (encapsulates common HTTP methods)

1 GET

2 POST

3 UIKit + AFNetWorking Classification

4 NSProgress (using KVO)

  • Semi-automatic serialization and deserialization

AFURLRequestSerialization: request data format/binary by default

AFURLResponseSerialization: Response Data Format/JSON format by default

  • Additional features

1. Security Policy: (HTTPS and AFSecurityPolicy)

2. network detection: (the link mode is encapsulated and AFNetWorkingReachabiliManager is used)

Link: http://www.cnblogs.com/worldtraveler/p/4736643.html

Steps for using AFN:

1. Create a request Operation Manager

2. Declare the response results for JSON, XML, and other Data parsing, and return Data

3. Set Request Parameters

4. Send a request

Supplementary ASI: (powerful, but not updated)

ASI steps:

1 get URL

2. Obtain the ASI request object

3 Send request

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.