HttpRequest POST, GET (NSURLConnection) II
Video Description
This is the second part of NSURLConnection tutorial. If you have not read or watched the first part, click here to watch it first. In this part we will learn how to create a GET and POST request.
How to create GET request
The following method will do the GET request- (void)httpGetRequest { NSString *str = @"http://content.guardianapis.com/search?api-key=test"; str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:str]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:GET]; self.restApi.delegate = self; [self.restApi httpRequest:request]; }In the first line we add the url address that we want to send the GET request. In the second line we convert the special characters of the url in first line. In the third like we convert the str into URL type that Objective-C can read it as an URL. In the fourth line we create our actual request with the URL we created. In the fifth line we specify the Http type (Here it's GET). The sixth line we are setting restApi delegate equal to self to implement RestApi class. In the last line we call RestAPI class to send our request (RestApi is created in previous session).
How to create POST request
- (void)httpPostRequest { NSString *postBody = @"api-key=test"; NSString *str = @"http://content.guardianapis.com/search"; str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:str]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:POST]; [request setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]]; self.restApi.delegate = self; [self.restApi httpRequest:request]; }It's exactly like sending GET request, the only difference is that it has 2 more lines. The first line and the seventh line. In the first line specifies the post body, which may includes post parameters. In the seventh line we attach the post body to the request.