iOS Network-nsurlconnection Simple Introduction

Source: Internet
Author: User

GET request

Sync Request (Get-sendsync)
(1) Steps
1 Setting the Request path
2 Create Request object (default is GET request, and the request header is already included by default)
3 Sending network requests using the Nsurlsession Sendsync method
4 after receiving the response from the server, parse the response body

(2) Related code

//1. Determine the request path//protocol Header + host address + interface name +?+ parameter 1& parameter 2& parameter 3Nsurl *url = [Nsurl urlwithstring:@"Http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"]; //2. Create a Request Object | GET//the request header is already included by default | Request Method (GET)Nsurlrequest *request =[[Nsurlrequest Alloc]initwithurl:url]; //3. Send Request (GET)//synchronization requests, blocking threads    /*first parameter: Request object second parameter: response header third parameter: Error message return value: NSData Type, response body information*/Nserror*error =Nil; Nsurlresponse*response =Nil; NSData*data = [Nsurlconnection sendsynchronousrequest:request returningresponse:&response error:&ERROR]; //4. Parsing Data    if(Error = =Nil) {NSLog (@"%@", [[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]); NSLog (@"%@---%@", Response,error); }

Asynchronous request (Get-sendasync)

(1) Related instructions
The method does not get stuck on the current thread, and the network request task is executed asynchronously

(2) Related code

    //1. Determine the request path//protocol Header + host address + interface name +?+ parameter 1& parameter 2& parameter 3Nsurl *url = [Nsurl urlwithstring:@"Http://120.25.226.186:32812/login?username=888&pwd=520it&type=JSON"]; //2. Create a Request Object | GET//the request header is already included by default | Request Method (GET)Nsurlrequest *request =[[Nsurlrequest Alloc]initwithurl:url]; //3. Sending an asynchronous request    /*first parameter: The second parameter of the Request object: queue, which determines which thread the block calls the third parameter: Completionhandler execute response when the request finishes (Success | failed): response header D ATA: Response body Information connectionerror: Error message*/[Nsurlconnection SendAs
Ynchronousrequest:request queue:[nsoperationqueue Mainqueue] Completionhandler:^ (Nsurlresponse * _nullable response, NSData * _nullable data, Nserror *_nullable Connectionerror) { //4. Parsing DataNSLog (@"%@", [[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]); }];

Asynchronous request (get-proxy)
(1) Steps
1 Determining the request path
2 Creating a Request object
3 Creating a Nsurlconnection object and setting up the proxy
4 comply with the Nsurlconnectiondatadelegate protocol and implement the appropriate proxy method
5 Listening for network request responses in Agent methods
(2) Several methods of setting up the agent

//1. Determine the request pathNsurl *url = [Nsurl urlwithstring:@"Http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"]; //2. Create a Request objectNsurlrequest *request =[Nsurlrequest Requestwithurl:url]; //3. Setting up the agent//the first way , the method automatically sends a network request    //nsurlconnection *connect = [[Nsurlconnection alloc]initwithrequest:request delegate:self]; //the second way, ibid.//[Nsurlconnection connectionwithrequest:request delegate:self]; //The third method of    /*first parameter: The second parameter of the Request object: Who becomes the agent the third parameter: startimmediately: Whether to start sending network requests immediately*/nsurlconnection*connect = [[Nsurlconnection alloc]initwithrequest:requestDelegate: Self startimmediately:no];
[connect start]; //[connect cancel];#pragmaMark-nsurlconnectiondatadelegate//1. Called when receiving a response from the server: Response (response header)-(void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{Self.filedata=[Nsmutabledata data]; NSLog (@"Didreceiveresponse");}//2. Called when the server returns data (will be called multiple times)-(void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{NSLog (@"didreceivedata---%zd", data.length); //Stitching Data[Self.filedata appenddata:data];}//3. Call when the request fails-(void) Connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{NSLog (@"Didfailwitherror");}//4. Call when the request finishes (Success | failed)-(void) Connectiondidfinishloading: (Nsurlconnection *) connection{NSLog (@"connectiondidfinishloading"); //parsing DataNSLog (@"%@", [[NSString Alloc]initwithdata:self.filedata encoding:nsutf8stringencoding]);}

POST request

(1) Send POST request step

A. Determining the URL path
B. Creating a Request object (Mutable object)
C. Modify the Request object by post, set the request body (Data)
D. Sending an asynchronous request
E. Add: Set request timeout, handle error message, set request header (such as Get client version etc, request header can be set not set)

(2) Related code

    //1. Determine the request pathNsurl *url = [Nsurl urlwithstring:@"Http://120.25.226.186:32812/login"]; //2. Create a Request objectNsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url]; //2.1 Change Request MethodRequest. HttpMethod =@"POST"; //2.2 Setting the request bodyRequest. Httpbody = [@"username=520it&pwd=520it"datausingencoding:nsutf8stringencoding]; //2.3 Request timed outRequest.timeoutinterval =5; //2.4 Setting the request header[Request SetValue:@"iOS 9.0"Forhttpheaderfield:@"user-agent"]; //3. Sending the request[Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse * __nullable response, NSData * __nullable data, Nserror *__nullable Connectionerror) {    //4. Parsing the data returned by the server        if(connectionerror) {NSLog (@"-- request failed-"); }Else{NSLog (@"%@", [[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]); }    }];

iOS Network-nsurlconnection Simple Introduction

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.