Saturday, September 1, 2012

Send HTTP Request and retrive HTTP response in iPhone, iPad Application

Hello,

Recently I was working on an iPhone application where requirement was to send HTTP request and retrieve the response. This was not a JSON or restful web service. Checkout the following code.


 NSMutableString* url = [NSMutableString string];
    [url appendString:@"http://www.example.com"];
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
        
        
    } else {
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Failed" message:@"Check your networking configuration." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
    }

Above code will initiate the connection. If it's successful it will go in if part else it will go in else part. On successful connection we have to retrive the data so we will add few delegates functions for it.

- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
       if ([httpResponse statusCode] >= 400) {
        // do error handling here
           UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Failed" message:@"Check your networking configuration." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
           [alertView show];
    } else {
        // start recieving data
    }
}

This function will be invoked when we have response. After we get response we will start fetching data. There is a separate delegate function for it.

-   (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData{
    NSString *response = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];

Above function will be invoked when we will have real data. Here response will give us data in string format.

Hope this helps.

No comments:

Post a Comment