Thursday, August 8, 2013

In this post, I will be talking about web requests and responses in Objective C for an IPhone app. The framework provides NS APIs to make URL Requests such as NSMutableURLRequest and NSURLConnection. Both GET and POST methods can be made with these. However, CFNetwork library is even more easier  to use for this. The caveat with most helper methods is that their quirks have to be understood The approach to use NSURLConnection is quite straightforward. However, setting and detecting proxies with this framework isn't as convenient as say in the ASI framework. In fact, ASI framework can not only detect the proxy settings and configurations, it can also specify another or with a .pac script file.  ASI wraps the CFProxySupportTool. Unlike the WinInet in Windows, the way to retrieve the proxy settings from iOS is via the high level wrapper APIs.

Here's an example:

   NSMutableURLRequest *request =
    [[NSMutableURLRequest alloc] initWithURL:
     [NSURL URLWithString:@"https://test.openapi.starbucks.com/v1/oauth/token"]];
    
    [request setHTTPMethod:@"POST"];
    
    NSString *postString = @"grant_type=client_credentials&client_id=your_client_id&client_secret=your_client_secret&scope=test_scope&api_key=your_api_key";
    
    [request setValue:[NSString
                       stringWithFormat:@"%d", [postString length]]
   forHTTPHeaderField:@"Content-length"];
    
    [request setHTTPBody:[postString
                          dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[NSURLConnection alloc]
     initWithRequest:request delegate:self];
    
    
}

No comments:

Post a Comment