O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.5. Sending HTTP GET Requests with NSURLConnection

Problem

You want to send a GET request over the HTTP protocol and perhaps pass parameters along your request to the receiver.

Solution

By convention, GET requests allow parameters through query strings of the familiar form:

http://example.com/?param1=value1&param2=value2...

You can use strings to provide the parameters in the conventional format.

Discussion

A GET request is a request to a web server to retrieve data. The request usually carries some parameters, which are sent in a query string as part of the URL.

In order to test a GET call, you need to find a web server that accepts the GET method and can send you some data back. This is simple. You may already know that when you open a web page in your browser, your browser by default sends a GET request to that end point, so you can use this recipe on any website of your liking.

To simulate sending query string parameters in a GET request to the same web service using NSURLConnection, use a mutable URL request and explicitly specify your HTTP method to GET using the setHTTPMethod: method of NSMutableURLRequest and put your parameters as part of the URL, like so:

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

    NSString *urlAsString = <# Place the URL of the web server here #>;
    urlAsString = [urlAsString stringByAppendingString:@"?param1=First"];
    urlAsString = [urlAsString stringByAppendingString:@"&param2=Second"];

    NSURL

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required