Sending an HTTP GET request via Nsurlconnection
//send a GET request to server with some params-(void) httpgetwithparams{NSString*urlstring =@"http://chaoyuan.sinaapp.com"; URLString= [URLString stringbyappendingstring:@"? p=1059"]; Nsurl*url =[Nsurl urlwithstring:urlstring]; Nsmutableurlrequest*urlrequest =[Nsmutableurlrequest Requestwithurl:url]; [URLRequest settimeoutinterval:30.0f]; [URLRequest Sethttpmethod:@"GET"]; Nsoperationqueue*queue =[[Nsoperationqueue alloc] init]; [Nsurlconnection sendasynchronousrequest:urlrequest queue:queue Completionhandler:^ (Nsurlresponse *response, NSData *data, Nserror *connectionerror) { if([Data length] >0&& Connectionerror = =Nil) {NSString*html =[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"HTML =%@", HTML); }Else if([data length] = =0&& Connectionerror = =Nil) {NSLog (@"Nothing is download."); }Else if(Connectionerror! =Nil) {NSLog (@"Error happened =%@", Connectionerror); } }];}
Sending an HTTP POST request via Nsurlconnection
//send a POST request to a server with some params-(void) httppostwithparams{NSString*urlasstring =@"http://chaoyuan.sinaapp.com"; Urlasstring= [Urlasstring stringbyappendingstring:@"? Param1=first"]; Urlasstring= [Urlasstring stringbyappendingstring:@"¶m2=second"]; Nsurl*url =[Nsurl urlwithstring:urlasstring]; NSString*body =@"bodyparam1=bodyvalue1&bodyparam2=bodyvalue2"; Nsmutableurlrequest*urlrequest =[Nsmutableurlrequest Requestwithurl:url]; [URLRequest settimeoutinterval:30.0f]; [URLRequest Sethttpmethod:@"POST"]; [URLRequest sethttpbody:[body datausingencoding:nsutf8stringencoding]; [URLRequest setvalue:[nsstring stringWithFormat:@"%lu", (unsignedLong) [body length]] Forhttpheaderfield:@"Content-length"]; [URLRequest SetValue:@"application/x-www-form-urlencoded"Forhttpheaderfield:@"Content-type"]; Nsoperationqueue*queue =[[Nsoperationqueue alloc] init]; [Nsurlconnection sendasynchronousrequest:urlrequest queue:queue Completionhandler:^ (Nsurlresponse *response, NSData *data, Nserror*error) { if([Data length] >0&&Error==Nil) {NSString*html = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"HTML =%@", HTML); //Show to UIWebView//[Self.bankwebview loaddata:data mimetype:@ "text/html" textencodingname:@ "UTF-8" baseurl:nil]; } Else if([data length] = =0&&Error==Nil) {NSLog (@"Nothing is downloaded."); } Else if(Error! =Nil) {NSLog (@"Error happened =%@", error); } }];}
Use of IOS development note-nsurlconnection