October 2013
Intermediate to advanced
1053 pages
28h 7m
English
You want to call a web service using the HTTP POST method, and perhaps pass parameters (as part of the HTTP body or in the query string) to the web service.
Just as with the GET method, we can use the POST method using
NSURLConnection. We must explicitly
set our URL’s method to POST.
Let’s write a simple app that can create an asynchronous connection and send a few parameters as a query string and a few parameters in the HTTP body to a URL:
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions{NSString*urlAsString=<#PlacetheURLofthewebserverhere#>;urlAsString=[urlAsStringstringByAppendingString:@"?param1=First"];urlAsString=[urlAsStringstringByAppendingString:@"¶m2=Second"];NSURL*url=[NSURLURLWithString:urlAsString];NSMutableURLRequest*urlRequest=[NSMutableURLRequestrequestWithURL:url];[urlRequestsetTimeoutInterval:30.0f];[urlRequestsetHTTPMethod:@"POST"];NSString*body=@"bodyParam1=BodyValue1&bodyParam2=BodyValue2";[urlRequestsetHTTPBody:[bodydataUsingEncoding:NSUTF8StringEncoding]];NSOperationQueue*queue=[[NSOperationQueuealloc]init];[NSURLConnectionsendAsynchronousRequest:urlRequestqueue:queuecompletionHandler:^(NSURLResponse*response,NSData*data,NSError*error){if([datalength]>0&&error==nil){NSString*html=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
Read now
Unlock full access