How to get the source code of a URL

Vikas Singh picture Vikas Singh · May 11, 2012 · Viewed 12.7k times · Source

I am not able to get the HTML source code when I try to request this URL: http://www.google.co.in/search?q=search

NSURL *url = [NSURL URLWithString:@"http://www.google.co.in/search?q=search"];

NSMutableURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSLog(@"Webdata : %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

The data is always NULL.

Answer

fbernardo picture fbernardo · May 11, 2012

This works:

NSURL *url = [NSURL URLWithString:@"http://www.google.co.in/search?q=search"]; 
NSString *webData= [NSString stringWithContentsOfURL:url]; 
NSLog(@"%@",webData);

But if you need to use a NSURLConnection you should use it asynchronously and implement the willSendRequest method to handle redirection.

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response;