First step: Abide by the Protocol agent Nsurlconnectiondatadelegate
Step Two: Network requests
//<1> Convert the URL of the POST request to a URLNsurl * url =[Nsurl Urlwithstring:path]; //<2> encapsulating Nsurl as a request object//GET Request object is Nsurlrequest//Post Request object is NsmutableurlrequestNsmutableurlrequest * Request =[Nsmutableurlrequest Requestwithurl:url]; //<3> Set the current request method, the default request style is a GET request[Request Sethttpmethod:@"Post"];//can be case -sensitive//<4> Set Request mode[Request SetValue:@"application/x-www-form-urlencoded"Forhttpheaderfield:@"Content-tpye"];//The second parameter is fixed, and the first one changes a total of 4 types as needed//<5> Stitching Request PathUitextfield * TF1 = (Uitextfield *) [Self.view Viewwithtag: -]; Uitextfield* TF2 = (Uitextfield *) [Self.view Viewwithtag:101]; Uitextfield* TF3 = (Uitextfield *) [Self.view Viewwithtag:102]; NSString* Bodystr = [NSString stringWithFormat:@"username=%@&password=%@&email=%@", Tf1.text,tf2.text,tf3.text]; //<6> Set the request length//setting the length of the request body is the length of the data for the NSData type of the request body//The string is converted to the data typeNSData * Bodydata =[Bodystr datausingencoding:nsutf8stringencoding]; [Request setvalue:[nsstring stringWithFormat:@"%d",(int) Bodydata.length] Forhttpheaderfield:@"Content-length"]; //set the request body[Request Sethttpbody:bodydata]; //<8> Start an asynchronous request[Nsurlconnection Connectionwithrequest:requestDelegate: Self];
Step three: Implement proxy methods
-(void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{if(_mydata = =Nil) {_mydata=[[Nsmutabledata alloc]init]; } Else{_mydata.length=0; }}-(void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{[_mydata appenddata:data];}-(void) Connectiondidfinishloading: (Nsurlconnection *) connection{//Perform data parsingNsdictionary * dic =[nsjsonserialization jsonobjectwithdata:_mydata options:nsjsonreadingmutablecontainers Error:nil]; NSString* Code = [dic objectforkey:@"Code"]; NSString* message = [dic objectforkey:@"message"]; if([Code isequaltostring:@"registed"]) {NSLog (@"Registration Successful"); } Else{NSLog (@"failure:%@", message); }}
Nsurlconnection making a POST request