Four: Basic use of network--nsurlconnection

Source: Internet
Author: User

First, the common class of Nsurlconnection

(1) Nsurl: Request Address

(2) Nsurlrequest: Encapsulates a request to save all data sent to the server, including a Nsurl object, request method, request header, request body ....

(3) Subclass of Nsmutableurlrequest:nsurlrequest. The request that he created can set a timeout for requests. Change Request method (default GET Request)

(4) Nsurlconnection: Responsible for sending the request to establish a connection between the client and the server. Send nsurlrequest data to the server and collect response data from the server

second, the use of Nsurlconnection1. Brief description

The steps to send a request using Nsurlconnection are simple

(1) Create a Nsurl object, set the request path (set the request path)

(2) Incoming Nsurl Create a Nsurlrequest object, set the request header and the request body (Create request object)

(3) Send nsurlrequest using nsurlconnection (send request)

2. Code examples

(1) Three steps to send a request:

1. Set the request path 2. Create Request object 3. Send Request 3.1 Send a synchronization request (always waiting for the server to return data, this line of code will get stuck, if the server, there is no return data, then the main thread UI will be stuck can not continue to perform operations) has a return value of 3.2 Send asynchronous Request: No return value description: Any nsurlrequest default is a GET request.
 1//Send Sync Request code example: 9 #import "YYViewController.h" #import "mbprogresshud+mj.h" @interface Yyviewcontroller () @pr Operty (Weak, nonatomic) Iboutlet Uitextfield *username;14 @property (weak, nonatomic) Iboutlet Uitextfield *pwd;15-(IBA ction) login;16 @end18 @implementation YYViewController20-(ibaction) Login {22//1. Advanced form verification of the IF (self.use rname.text.length==0) {Mbprogresshud showerror:@ "Please enter user name"];25 return;26}27 if (self.pwd.text.l ength==0) {Mbprogresshud showerror:@ "Please enter password"];29 return;30}31//2. Send request to server (with account number and password) 32//Add A mask that prohibits user action//[Mbprogresshud showmessage:@ "is trying to load ...."];34//GET request: Request line \ request header \ Request Body 35//36//1. Set Request Path PNS NSSt Ring *urlstr=[nsstring stringwithformat:@ "http://192.168.1.53:8080/mjserver/login?username=%@&pwd=%@", self.username.text,self.pwd.text];38 nsurl *url=[nsurl urlwithstring:urlstr];39//2. Create Request object Max NSURLRequest *req Uest=[nsurlrequest requestwithurl:url];41//3. Send a request 42//Send a sync request on the main thread to execute NSData *data=[nsurlconnection sendsynchronousrequest:request returningresponse: Nil error:nil];44//(always waiting for the server to return data, this line of code will be stuck, if the server does not return data, then the main thread UI will be stuck can not continue to perform operations) NSLog (@ "--%d--", data.length); 46}47 @ End
Simulator Case:
      
Additional instructions: 1. Advanced Form validation 2. Send request to server (with account and password) GET request: Request line \ request header \ Request Body Note: The request body does not exist in the GET request because all the information is written in the URL. In iOS, both the request line and the request header are not written. (3) There are two ways to send an asynchronous request to send an asynchronous request: 1) using block callback 2) proxy A. Sending an asynchronous request using the block callback method   
9 Example of using block callback code: Ten #import "Mbprogresshud+mj.h" @interface Yyviewcontroller () @property (weak, nonatomic) Iboutle T Uitextfield *username;14 @property (weak, nonatomic) Iboutlet Uitextfield *pwd;15-(ibaction) login;16 @end18 @imp         Lementation YYViewController20-(ibaction) Login {22//1. Pre-order Form validation for (self.username.text.length==0) {24 [Mbprogresshud showerror:@ "Please enter user name"];25 return;26}27 if (self.pwd.text.length==0) {[Mbprogres]  Shud showerror:@ "Please enter password"];29 return;30}31//2. Send a request to the server (with an account number and password) 32//Add a mask that prohibits user operation [Mbprogresshud showmessage:@ "is trying to load ..."];34 35//36//1. Set Request path PNS nsstring *urlstr=[nsstring stringwithformat:@ "http://192.168. 1.53:8080/mjserver/login?username=%@&pwd=%@ ", self.username.text,self.pwd.text];38 NSURL *url=[NSURL    URLWITHSTRING:URLSTR];39 40//2. Create Request object Nsurlrequest *request=[nsurlrequest requestwithurl:url];42 43// 3. Send request 44//3.1 Send synchronization request, execute 45//on main thread    NSData *data=[nsurlconnection sendsynchronousrequest:request Returningresponse:nil error:nil];46//(has been waiting for the server to return data, which  The line code will be stuck, if the server does not return data, then the main thread UI will be stuck unable to proceed with the operation) 47 48//3.1 Send an asynchronous request 49//Create a queue (the task that is added to the queue asynchronously executes by default)//Nsoperationqueue     *queue=[[nsoperationqueue alloc]init];51//Get a home row nsoperationqueue *queue=[nsoperationqueue mainQueue];53 [Nsurlconnection sendasynchronousrequest:request queue:queue completionhandler:^ (NSURLResponse *response, NSData *         Data, Nserror *connectionerror) {NSLog (@ "--block callback--%@---%d", [Nsthread currentthread],data.length); 55 Hide the HUD, refresh the UI must be placed on the main thread to perform the [Mbprogresshud hidehud];57 58//Parse Data59/*60 {"succ ESS ":" Login Successful "}61 {" error ":" User name does not exist "}62 {" error ":" Password incorrect "}63 */64 nsdictionary *dict=[nsjsonse         Rialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves error:nil];65 NSLog (@ "%@", dict); 66    67//Judging after the interface prompts for login information 68     NSString *error=dict[@ "Error"];69 if (error) {[Mbprogresshud showerror:error];71}else         NSString *success=dict[@ "Success"];74 [Mbprogresshud showsuccess:success];75 }76}];77 NSLog (@ "Request sent complete");}79 @end
Text top-top iOS Development Network Chapter-nsurlconnection Basic use

iOS Development Network Chapter-nsurlconnection Basic use

First, the common class of Nsurlconnection

(1) Nsurl: Request Address

(2) Nsurlrequest: Encapsulates a request to save all data sent to the server, including a Nsurl object, request method, request header, request body ....

(3) Subclass of Nsmutableurlrequest:nsurlrequest

(4) Nsurlconnection: Responsible for sending the request to establish a connection between the client and the server. Send nsurlrequest data to the server and collect response data from the server

second, the use of Nsurlconnection1. Brief description

The steps to send a request using Nsurlconnection are simple

(1) Create a Nsurl object, set the request path (set the request path)

(2) Incoming Nsurl Create a Nsurlrequest object, set the request header and the request body (Create request object)

(3) Send nsurlrequest using nsurlconnection (send request)

2. Code examples

(1) Three steps to send a request:

1. Set request path 2. Create Request object 3. Send Request 3.1 Send a synchronization request (always waiting for the server to return data, this line of code will get stuck, if the server, there is no return data, then the main thread UI will be stuck can not continue to perform operations) has a return value 3.2 sends an asynchronous request: no return value description: any nsurlrequest is a GET request. (2) Example of sending a synchronous request code:
 1//2//YYVIEWCONTROLLER.M 3//01-nsurlconnection use (GET) 4//5//Created by Apple on 14-6-28. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" #import "mbprogresshud+mj.h" @interface Yyviewcontroller () @property (WEA K, nonatomic) Iboutlet Uitextfield *username;14 @property (weak, nonatomic) Iboutlet Uitextfield *pwd;15-(IBAction) login ; @end18 @implementation YYViewController20-(ibaction) Login {22//1. Advanced Forms verify the (self.username.text. length==0) {Mbprogresshud showerror:@ "Please enter user name"];25 return;26}27 if (self.pwd.text.length==0) { [Mbprogresshud showerror:@ "Please enter your password"];29 return;30}31//2. Send request to server (with account number and password) 32//Add a mask to prevent user action [Mbprogresshud showmessage:@] is trying to load .... "];34//GET request: Request line \ request header \ Request Body 35//36//1. Set Request path PNS NSString *urlst R=[nsstring stringwithformat:@ "http://192.168.1.53:8080/mjserver/login?username=%@&pwd=%@", Self.username.text,self.pwd.text];38 nsurl *url=[nsurl urlwithstring:urlstr];39//2. Create Request object Max Nsurlrequest *request=[nsurlreq Uest requestwithurl:url];41//3. Send a request 42//Send a sync request, perform a nsdata *data=[nsurlconnection sendsynchronousrequest on the main thread: Request Returningresponse:nil error:nil];44//(always waiting for the server to return data, this line of code will be stuck, if the server does not return data, then the main thread UI will be stuck can not continue to perform operations) NSLog (@ "--% d--", data.length);}47 @end

Simulator Case:

Information returned by the print server:

  

Additional instructions: 1. Advanced Form validation 2. Send request to server (with account and password) GET request: Request line \ request header \ Request Body Note: The request body does not exist in the GET request because all the information is written in the URL. In iOS, both the request line and the request header are not written. (3) There are two ways to send an asynchronous request to send an asynchronous request: 1) using block callback 2) proxy A. Sending an asynchronous request using the block callback methodExample of using block callback code:
 1//2//YYVIEWCONTROLLER.M 3//01-nsurlconnection use (GET) 4//5//Created by Apple on 14-6-28. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" #import "mbprogresshud+mj.h" @interface Yyviewcontroller () @property (WEA K, nonatomic) Iboutlet Uitextfield *username;14 @property (weak, nonatomic) Iboutlet Uitextfield *pwd;15-(IBAction) login ; @end18 @implementation YYViewController20-(ibaction) Login {22//1. Advanced Forms verify the (self.username.text. length==0) {Mbprogresshud showerror:@ "Please enter user name"];25 return;26}27 if (self.pwd.text.length==0) { [Mbprogresshud showerror:@ "Please enter your password"];29 return;30}31//2. Send request to server (with account number and password) 32//Add a mask to prevent user action [Mbprogresshud showmessage:@] is trying to load .... "];34 35//36//1. Set Request path PNS NSString *urlstr=[nsstring stringwithfor   mat:@ "http://192.168.1.53:8080/mjserver/login?username=%@&pwd=%@", self.username.text,self.pwd.text];38  Nsurl *url=[nsurl urlwithstring:urlstr];39 40//2. Create Request object Nsurlrequest *request=[nsurlrequest Requestwithur L:URL];42 43//3. Send request 44//3.1 send sync request, execute on main thread//NSData *data=[nsurlconnection sendsynchronousrequest:reques T Returningresponse:nil error:nil];46//(always waiting for the server to return data, this line of code will be stuck, if the server does not return data, then the main thread UI will be stuck can not continue to perform operations) 47 48//3.1 Send asynchronous please Request 49//Create a queue (the task that is added to the queue by default executes asynchronously)//Nsoperationqueue *queue=[[nsoperationqueue alloc]init];51//Get a home row of N Soperationqueue *queue=[nsoperationqueue mainqueue];53 [nsurlconnection sendasynchronousrequest:request Queue:queue completionhandler:^ (Nsurlresponse *response, NSData *data, Nserror *connectionerror) {si NSLog (@ "--block callback data--%@--         -%d ", [Nsthread currentthread],data.length); 55//Hide HUD, Refresh UI action must be placed on the main thread to perform the [Mbprogresshud hidehud];57 58//Parse Data59/*60 {"Success": "Login succeeded"}61 {"error": "User name does not exist"}62 {"error": "Password Incorrect"} */64 NSdictionary *dict=[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves error:nil];65 NS             Log (@ "%@", dict); 66 67//After judging, the interface prompts for login information nsstring *error=dict[@ "error"];69 if (error) {70 [Mbprogresshud showerror:error];71}else72 {nsstring *success=dict[@ "success"];7 4 [Mbprogresshud showsuccess:success];75}76}];77 NSLog (@ "Request sent complete");}79 @end

Simulator situation (note that a third-party framework is used here):

  

Print View:

  

Code Description: Block Code snippet: When the server has the return data when the call will open a new thread to send the request, the main thread continues to go down, when the data returned to the server back to block, execute block code snippet.  This situation does not get stuck in the main thread.  The role of the queue: decide which thread the block operation is to execute on?  The action of refreshing the UI interface should be placed on the main thread execution, cannot be placed on child threads, and there are some inexplicable problems with the child threading UI related operations.    Tip: (1) Create an action that is executed in the Nsoperation queue, which is executed asynchronously by default.   (2) Mainqueue returns a queue associated with the main thread, that is, the home column. New problem: If you send a request to the server but do not get the data, the program crashes (data cannot be empty) to improve the code:
 1 nsoperationqueue *queue=[nsoperationqueue Mainqueue]; 2 [nsurlconnection sendasynchronousrequest:request queue:queue completionhandler:^ (NSURLResponse *response, NSData *d ATA, Nserror *connectionerror) {3//When the request ends (there are two results, one is to successfully get the data, or not to get the data, the request fails) 4 NSLog (@ "--block callback data--%@- --%d ", [Nsthread currentthread],data.length); 5//Hide HUD, refresh UI must be placed in the main thread execution 6 [Mbprogresshud Hidehud]; 7 8//Parse data 9/*10 {"Success": "Login Successful"}11 {"error": "User name does not exist"}12 {"error": "Secret Code is incorrect "}13 */14 if (data) {///request successfully nsdictionary *dict=[nsjsonserialization Jsonobjectwithdata: Data options:nsjsonreadingmutableleaves error:nil];16 NSLog (@ "%@", Dict); 17 18//judgment, in the bounded Face hint Login information nsstring *error=dict[@ "error"];20 if (error) {[Mbprogresshud Showerro r:error];22}else23 {nsstring *success=dict[@ "SucceSS "];25 [Mbprogresshud showsuccess:success];26}27}else//Request failed 28 {29 [Mbprogresshud showerror:@] Network busy, please try again later! "];30}31 32}];
Supplemental Note: First determine the request path, and then create the request object (the default is sent when the GET request), using an asynchronous method (call this method, it will automatically open a child thread to send the request, when the request is successful, the data returned automatically call the internal code snippet, the code snippet in that thread execution depends on the queue, If it is the home row, then after the child thread sends the request to the server's data, it goes back to the main thread to parse the data and refresh the UI interface. B. Sending an asynchronous request using the Proxy method to listen to the data returned by the server, use the <NSURLConnectionDataDelegate> protocol common proxy methods are as follows
1 #pragma mark-nsurlconnectiondatadelegate proxy Method 2  3//4  5-(void) connection are called when the response to the server is received (the server is connected): ( Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) Response 6  7//When data received from the server is called (may be called multiple times, Transfer only partial data at a time) 8  9-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data10 11// When the data of the server is loaded, it is called (void) connectiondidfinishloading: (nsurlconnection *) connection14 15//Request error (failed) call (Request timed out \ Network off \ No net \, generally referred to as client error)-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error

Sample code to send a GET request using an Async method
  9 #import "YYViewController.h" #import "mbprogresshud+mj.h" @interface Yyviewcontroller () <nsurlconnectiond Atadelegate> @property (Weak, nonatomic) Iboutlet Uitextfield *username; @property (Weak, nonatomic) Iboutlet Uitextfield *pwd; @property (Nonatomic,strong) Nsmutabledata *responsedata; -(ibaction) login; @end @implementation Yyviewcontroller-(ibaction) Login {23//1. Advanced form verification of the IF (self.username . text.length==0) {[Mbprogresshud showerror:@ "Please enter user name"];     ngth==0) {Mbprogresshud showerror:@ "Please enter the password"]; 31} 32//2. Send the request to the server (with account number and password) 33 Add a mask that prohibits user action [Mbprogresshud showmessage:@ "is trying to load ....]; 35 36//37//2.1 Set Request path NSString *urlstr=[nsstring stringwithformat:@ "Http://192.168.1.53:8080/MJServer/login?u sername=%@&pwd=%@ ", Self.username.text,self.pwd.text]; Nsurl *url=[nsurl URLWITHSTRING:URLSTR]; 40 41//2.2 Create Request object *request=[nsurlrequest//nsurlrequest requestwithurl:url];//default is GET request 43//Set Request Timeout 44 Nsmutableurlrequest *request=[nsmutableurlrequest Requestwithurl:url]; request.timeoutinterval=5.0; 46 47//2.3. Send request 48//Send an asynchronous request using a proxy (typically applied to a file download) nsurlconnection *conn=[nsurlconnection connectionwithrequest:r Equest Delegate:self]; [Conn start]; NSLog (@ "has issued a request---"); #pragma mark-nsurlconnectiondatadelegate Agent Method 55/* 56 * When receiving a response from the server (connected to the server) will call the "* * * * * * (void) connection: (N Surlconnection *) connection didreceiveresponse: (Nsurlresponse *) Response (@ "Receive server response"), 61//Initialize Data 6 2 Self.responsedata=[nsmutabledata data]; 63} 64 65/* 66 * will be called when receiving data from the server (may be called multiple times, only part of the data will be delivered at a time) */-(void) connection: (Nsurlconnection *) connection didreceived ATA: (NSData *) data, {NSLog (@ "Data received from the server"); 71//splicing data [Self.responsedata Appenddata:data]; SLog (@ "%d---%@--", self.responsedata.lEngth,[nsthread CurrentThread]);     74} 75 76/* 77 * When the server's data has been loaded, it will call the connectiondidfinishloading */-(void): (nsurlconnection *) connection 80 {81 NSLog (@ "Server data load Complete"); 82//Hide HUD [Mbprogresshud Hidehud]; 84 85//Processing all data returned by the server nsdictionary *dict=[nsjsonserialization JSONObjectWithData:self.responseData options: Nsjsonreadingmutableleaves Error:nil]; 87 88//After judging the login information in the interface nsstring *error=dict[@ "error"; if (error) {[Mbprogresshud showerror:error];}else 94 NSString *success=dict[@ " Success "]; [Mbprogresshud showsuccess:success]; NSLog (@ "%d---%@--", self.responsedata.length,[nsthread CurrentThread]); 98} 99/*100 * Request Error (failed) call (Request timed out \ off net \ No net \, usually referred to as client error) 101 */102-(void) connection: (Nsurlconnection *) connection Didfailwitherror: (Nserror *) error103 {104//NSLog (@ "request Error"); 105//Hide HUD106 [Mbprogresshud hidehud];107 [MB] Progresshud showerror:@ "The network is busy, please try again later! "];108}109 @end 

Add:

(1) Processing of data

In the Didreceivedata: method, all the data received by stitching, and all the data are obtained, are processed in the connectiondidfinishloading: method.

(2) Network latency

When doing network development, be sure to take into account the network delay situation of processing, you can set a breakpoint in the server code simulation.

To set breakpoints in the logon method of server code

    

Set the maximum delay for a request

    

Third, Nsmutableurlrequest

Nsmutableurlrequest is a subclass of nsurlrequest, the common method is

Set the request timeout wait time (more than this time to timeout, request failed)-(void) Settimeoutinterval: (nstimeinterval) seconds;

Set the request method (such as Get and post)-(void) Sethttpmethod: (NSString *) method;

Set the request body-(void) Sethttpbody: (NSData *) data;

Set Request Header-(void) SetValue: (NSString *) value Forhttpheaderfield: (NSString *) field;

Four: Basic use of network--nsurlconnection

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.