Get & Post Requests
• Four steps for network access
– Address – Request – connection – Processing result iOS network processing common class –nsurl (address) –nsrequest[get]& Nsmutableurlrequest[post] (Request) –nsconnection (connection) · The implementation of the Nsurlconnectiondatadelegate proxy method can receive server response data (processing results) about the agent: • Problems with proxy methods – more proxy methods, more decentralized – to process a request, you need to write code in many places – not for logical implementations, Code authoring, debugging, maintenance, and scaling – especially when there are multiple requests! • Agent methods that have been learned –uiapplicationdelegate–uitableviewdelegate, uitableviewdatasource–uitextfielddelegate– Custom proxy method via protocol – Nsurlconnectiondatadelegate Synchronous and asynchronous requests: Nsurlconnection provides two static methods that can call nsurlrequest directly or asynchronously. Without having to get data through Nsurlconnectiondatadelegate • Sync requests:
Sendsynchronousrequest:request Returningresponse:&response Error:&error
• Asynchronous Request:
Sendasynchronousrequest:request Queue:[nsoperationqueue Mainqueue] completionhandler:^ (NSURLResponse *response, NSData *data, Nserror *error)
For the contents of the main action queue, explain in the multithreading course
Cache policy: The CachePolicy property of Nsurlrequest can set the cache policy, which is a memory cache, not a hard disk cache • The purpose of using the cache is to use the application to respond more quickly to user input and to make the program run efficiently. Sometimes we need to cache the data obtained from the remote Web server and reduce the caching policies that are supported by multiple requests to the same URL cachepolicy: –nsurlrequestuseprotocolcachepolicy The default cache policy, To specify cache logic in the implementation method of the Protocol –nsurlrequestreloadignoringcachedata ignore the cache download from the original address –nsurlrequestreturncachedataelseload When no cache is downloaded from the original address, the –nsurlrequestreturncachedatadontload only uses the cache, and if there is no cache, the request fails and applies to the offline mode without establishing a network connection – Nsurlrequestreloadignoringlocalandremotecachedata ignore local and remote cache data, download directly from the original address, similar to Nsurlrequestreloadignoringcachedata –nsurlrequestreloadrevalidatingcachedata Verify that local data is the same as remote data, and download remote data if different, otherwise use local data
Synchronizing request data can cause the main thread to block, and it is often not recommended when big data is requested or the network is not smooth.
As you can see from the code above, the steps to establish communication are basically the same regardless of the synchronous request or the asynchronous request:
1. Create Nsurl
2. Create a Request object
3. Create a nsurlconnection connection.
Once the nsurlconnection is created, an HTTP connection is created. The difference between an asynchronous request and a synchronous request is that an asynchronous request is created, the user can do other things, the request is executed on another thread, and the communication results and procedures are executed in the callback function. Synchronization requests are different and require the end user to be requested to do other things.
(Learn about the basics of the network today, the code has a few duplicates, the caching strategy hasn't been learned yet)
Here is the code for Get and Post methods:
#pragmaMark-Test Get mode-(ibaction) GetLogin: (UIButton *) btn{StaticNSString * loginurl =@"http://192.168.1.102:8080/IOSApplication/LoginServletController.do"; //Initializing Data_receivedate =[Nsmutabledata data]; //Defining URLsNSString * Urlstr = [NSString stringWithFormat:@"%@?username=%@&password=%@", Loginurl,_username.text,_password.text]; //Note: The URL of the network request, need to encode before you can use!!! _Nsurl *url =[Nsurl Urlwithstring:urlstr]; ////Definition RequestNsurlrequest *request =[Nsurlrequest Requestwithurl:url]; //Defining ConnectionsNsurlconnection *cont = [[Nsurlconnection alloc] Initwithrequest:requestDelegate: Self]; [Cont start];}#pragmaMark-Network connection error judgment-(void) Connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{NSLog (@"Network connection Error%@", error.localizeddescription);}#pragmaMark-Receive response-(void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{NSLog (@"response to start receiving");}#pragmaMark-Received Data-(void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{NSLog (@"received data returned by the server:%@", data); [_receivedate appenddata:data];}#pragmaMark-End of connection-(void) Connectiondidfinishloading: (Nsurlconnection *) connection{NSString*backstring =[[NSString alloc]initwithdata:_receivedate encoding:nsutf8stringencoding]; NSLog (@"end the received data%@", backstring); _receivedate=Nil;}#pragmaMark-Test Post mode-(ibaction) Postlogin: (UIButton *) btn{StaticNSString * loginurl =@"http://192.168.1.102:8080/IOSApplication/LoginServletController.do"; //Initializing Data_receivedate =[Nsmutabledata data]; //a URL that defines a URL, which consists of letters and numbers, does not need to be encodedNsurl * url =[Nsurl Urlwithstring:loginurl]; //Defining RequestsNsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url]; //waiting for server response time 5[Request Settimeoutinterval:5.0]; //Set Request Mode[Request Sethttpmethod:@"Post"]; NSString*bodystring = [NSString stringWithFormat:@"username=%@&password=%@", _username.text,_password.text]; //generate request data and encodeNSData *body =[bodystring datausingencoding:nsutf8stringencoding]; //set the HTTP request data body, Nsmutableurlrequest will automatically add Content-length in the request header[Request Sethttpbody:body]; //Setting up ConnectionsNsurlconnection *cont = [[Nsurlconnection alloc]initwithrequest:requestDelegate: Self]; //Start Connection[cont start]; }#pragmaMark-Send data to the server, post requests use this method-(void) Connection: (Nsurlconnection *) connection Didsendbodydata: (Nsinteger) Byteswritten Totalbyteswritten: (Nsinteger) Totalbyteswritten Totalbytesexpectedtowrite: (Nsinteger) totalbytesexpectedtowrite{NSLog (@"send data to server Byteswritten:%ld, Totalbyteswritten%ld totalbytesexpectedtowrite%ld", Byteswritten,totalbyteswritten,totalbytesexpectedtowrite);}
The following are synchronous and asynchronous (Nsurlconnection provides two static methods that can call nsurlrequest directly or asynchronously without obtaining data through nsurlconnectiondatadelegate)
//generate a POST request-(Nsmutableurlrequest *) postloginrequest{StaticNSString * loginurl =@"http://192.168.1.102:8080/IOSApplication/LoginServletController.do"; //Initializing Data_receivedate =[Nsmutabledata data]; //a URL that defines a URL, which consists of letters and numbers, does not need to be encodedNsurl * url =[Nsurl Urlwithstring:loginurl]; //Defining RequestsNsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url]; //waiting for server response time 5[Request Settimeoutinterval:5.0]; //Set Request Mode[Request Sethttpmethod:@"Post"]; NSString*bodystring = [NSString stringWithFormat:@"username=%@&password=%@", _username.text,_password.text]; //generate request data and encodeNSData *body =[bodystring datausingencoding:nsutf8stringencoding]; //set the HTTP request data body, Nsmutableurlrequest will automatically add Content-length in the request header[Request Sethttpbody:body]; returnrequest;}#pragmaMark-post Sync Mode Login-(ibaction) Synchronizationlogin: (UIButton *) btn{nsmutableurlrequest*request =[self postloginrequest]; Nserror*error; Nsurlresponse*response; NSDate* date = [Nsurlconnection sendsynchronousrequest:request returningresponse:&response error:&ERROR]; //Note that subsequent actions are performed only after the synchronization request has ended, and modifying Login_url can see the effect if(!date) {NSLog (@"Sync Access error:%@", error.localizeddescription); } Else{ //Decoding DataNSString *string=[[NSString alloc]initwithdata:date encoding:nsutf8stringencoding]; NSLog (@"Synchronizing Data%@",string); }}#pragmaMark-post Asynchronous Login-(ibaction) Asynchronizationlogin: (UIButton *) btn{nsmutableurlrequest*request =[self postloginrequest]; //Note that the block code is used here! The asynchronous request queue uses the primary queue for the action queue[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 (@"the data that was successfully returned asynchronously%@",string); } Else if([Data length] <=0&& connectionerror==Nil) {NSLog (@"no return data received"); } Else{NSLog (@"Async Access Error%@", connectionerror.localizeddescription); } }];}
iOS Learning-Network Fundamentals