iOS Development Network chapter-Send get and POST requests (using Nsurlsession)
Description
1) This article mainly describes how to use Nsurlsession to send get requests and post requests
2) This article will no longer explain the use of nsurlconnection, if you need to know how nsurlconnection send the request.
For more information, please refer to: http://www.cnblogs.com/wendingding/p/3813706.html
3) The sample code sent by this article is an HTTP request that has been configured for the Info.plist file.
How to configure, please refer to: https://github.com/HanGangAndHanMeimei/iOS9AdaptationTips
4) The sample code for this article can be obtained at the following address:
Https://github.com/HanGangAndHanMeimei/Code
A simple explanation
After iOS9.0, the previously used nsurlconnection expires, and Apple recommends using Nsurlsession to replace the nsurlconnection to complete the network request-related operations.
The use of nsurlsession is simple, by creating a request task based on the session object, and then executing the task.
Nsurlsessiontask itself is an abstract class that, when used, usually uses several subclasses of it depending on the specific requirements. The relationship is as follows:
Second, send a GET request
The method to send a GET request using Nsurlsession is similar to nsurlconnection, the whole process is as follows:
1) Determine the request path (typically provided by the company's background developer as an interface document), and get request parameters directly following the URL
2) Create the Request object (which contains the request header and the request method "GET" by default), this step can omit
3) Create Session object (Nsurlsession)
4) Create a request task based on the Session object (Nsurlsessiondatatask)
5) Execute Task
6) When the response returned by the server is obtained, parse the data (xml| json| HTTP)
Example code:
the first method of sending a GET requestthe second method of sending a GET request
Execution Result:
The value printed here is a dictionary, the dictionary success the key corresponding to the value printed out for Unicode encoding, if you want to output Chinese, you can provide a classification for nsdictionary, rewrite the method in the system.
overriding system methods in dictionary classification
Execution Result:
Third, send the POST request
Using Nsurlsession to send a POST request is similar to nsurlconnection, the whole process is as follows:
1) Determine the request path (typically provided by the company's background developer in the form of an interface document)
2) Create a mutable request object (because it needs to be modified), this step cannot be omitted
3) Modify the request method to post
4) Set the request body, convert the parameters into binary data and set the request body
5) Create Session object (Nsurlsession)
6) Create a request task based on the Session object (Nsurlsessiondatatask)
7) Execute Task
8) When the response returned by the server is obtained, parse the data (xml| json| HTTP)
Example code:
How to send a POST request
Iv. Brief introduction of Nsurlsession agent method
Sometimes, we may need to listen to the process of network requests (such as downloading files to listen to file download progress), then you need to use the proxy method.
The next step in the code is to explain the use of proxy methods in general network requests in Nsurlsession
1 #import "ViewController.h" 2 3 @interface Viewcontroller () <NSURLSessionDataDelegate> 4 @property (nonatomic, St Rong) Nsmutabledata *responsedata; 5 @end 6 7 @implementation Viewcontroller 8 9-(Nsmutabledata *) responseData10 {one-if (_responsedata = = nil) {12 _responsedata = [Nsmutabledata data];13}14 return _responsedata;15}16 17//The method is called when the controller view is clicked-(void) TOU Chesbegan: (Nsset<uitouch *> *) touches withevent: (uievent *) event19 {[Self delegatetest];21}22 23//Send request, Proxy method (void) DelegateTest25 {26//1. Determine request path Nsurl *url = [Nsurl urlwithstring:@ "Http://120.25.226.186:32812/login?us Ername=520it&pwd=520it&type=json "];28 29//2. Create Request Object 30//Request Object The internal default already contains the request header and request method (GET) to Nsurlrequest *request = [Nsurlrequest requestwithurl:url];32 33//3. Get the Session object and set proxy 34/*35 The first parameter: configuration information for the session object Defaultsessionc Onfiguration represents the default configuration 36 the second parameter: who becomes the proxy, which is the controller itself, self37 the third parameter: queue, which determines which thread the proxy method is called in, and can pass the primary queue | Not the home row [NsopErationqueue Mainqueue] Home column: Proxy method called in the main thread [[Nsoperationqueue Alloc]init] Non-Home column: Proxy method calls in a child thread. */41 Nsurl Session *session = [nsurlsession sessionwithconfiguration:[nsurlsessionconfiguration defaultsessionconfiguration] Delegate:self delegatequeue:[nsoperationqueue mainqueue]];42 43//4. Create a task based on the session object (send request) Nsurlsessiondatatas K *datatask = [session datataskwithrequest:request];45 46//5. Perform task [Datatask resume];48}49 50//1. Receiving a response from the server Time to call this method-(void) Urlsession: (Nsurlsession *) session Datatask: (Nsurlsessiondatatask *) Datatask Didreceiveresponse: ( Nsurlresponse *) Response Completionhandler: (void (^) (nsurlsessionresponsedisposition)) completionHandler52 {53// In this method, the response header information can be obtained, namely response54 NSLog (@ "didreceiveresponse--%@", [Nsthread CurrentThread]); 55 56//NOTE: You need to use the completion Handler callback tells the system what to do with the data returned by the server 57//default is canceled/*59 nsurlsessionresponsecancel = 0, default processing mode, cancel 60 Nsurlsessionresponseallow = 1, the receiving server returnsData of Nsurlsessionresponsebecomedownload = 2, becomes a download request nsurlsessionresponsebecomestream into a stream 63 */64 Completionhandler (Nsurlsessionresponseallow); 66}67 68//2. This method is called when the server returns data, and if the data is large then the method may call multiple times-(v OID) Urlsession: (Nsurlsession *) session Datatask: (Nsurlsessiondatatask *) datatask didreceivedata: (NSData *) Data70 {71 NSLog (@ "didreceivedata--%@", [Nsthread CurrentThread]); 72 73//splicing data returned by the server [Self.responsedata Appenddata:data] ; 75}76 77//3. This method is called when the request completes (Success | fails), and if the request fails, error has a value of-(void) Urlsession: (Nsurlsession *) session task: ( Nsurlsessiontask *) Task Didcompletewitherror: (Nserror *) error79 {NSLog (@ "didcompletewitherror--%@", [Nsthread CurrentThread]); Bayi if (Error = = nil) 83 {84//parse data, JSON parsing refer to http://www.cnblogs.com/wendingding/p/3815 303.html85 nsdictionary *dict = [nsjsonserialization JSONObjectWithData:self.responseData options:kniloptions Erro r:nil];86 NSLog (@ "%@", dict); 87}88}89 @end
Code Execution Results:
Label
iOS Development Network chapter-Send get and POST requests (using Nsurlsession)