Vikas Singh
Vikas Singh

Reputation: 1791

How to get the source code of a URL

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.

Upvotes: 2

Views: 12796

Answers (5)

Leszek Szary
Leszek Szary

Reputation: 10356

Simple async solution with GCD:

- (void)htmlFromUrl:(NSString *)url handler:(void (^)(NSString *html, NSError *error))handler
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        NSError *error;
        NSString *html = [NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSASCIIStringEncoding error:&error];
        dispatch_async(dispatch_get_main_queue(), ^(void){
            if (handler)
                handler(html, error);
        });
    });
}

then

[self htmlFromUrl:@"http://stackoverflow.com" handler:^(NSString *html, NSError *error) {
    NSLog(@"ERROR: %@ HTML: %@", error, html);
}];

Upvotes: 1

F.b. Eyephone
F.b. Eyephone

Reputation: 41

The simple version:

NSURL *TheUrl = [NSURL URLWithString:@"http://google.com"];

NSString *webData = [NSString stringWithContentsOfURL:TheUrl 
                              encoding:NSASCIIStringEncoding
                              error:nil];

NSLog(@"%@", webData);

Upvotes: 4

Alphapico
Alphapico

Reputation: 3043

For asynchronous fetch of HTML source code, I recommend you to use AFNetworking

1) Then subclass AFHTTPCLient, for example:

//WebClientHelper.h
#import "AFHTTPClient.h"

@interface WebClientHelper : AFHTTPClient{

}

+(WebClientHelper *)sharedClient;

@end

//WebClientHelper.m
#import "WebClientHelper.h"
#import "AFHTTPRequestOperation.h"

NSString *const gWebBaseURL = @"http://dummyBaseURL.com/";


@implementation WebClientHelper

+(WebClientHelper *)sharedClient
{
    static WebClientHelper * _sharedClient = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:gWebBaseURL]];
    });

    return _sharedClient;
}

- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }

    [self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    return self;
}
@end

2) Request asynchronously HTML source code, put this code in any relevant part

NSString *testNewsURL = @"http://whatever.com";
    NSURL *url = [NSURL URLWithString:testNewsURL];
    NSURLRequest *request  = [NSURLRequest requestWithURL:url];

    AFHTTPRequestOperation *operationHttp =
    [[WebClientHelper sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSString *szResponse = [[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] autorelease];
         NSLog(@"Response: %@", szResponse );
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Operation Error: %@", error.localizedDescription);
     }];

    [[WebClientHelper sharedClient] enqueueHTTPRequestOperation:operationHttp];

Upvotes: 0

fbernardo
fbernardo

Reputation: 10124

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;

Upvotes: 6

Abhishek Singh
Abhishek Singh

Reputation: 6166

You can get the data in following ways :-

1 .Using NSUrlConnection as asynchronous reuest

2. Synchronous NSUrlConnection

NSURL *URL = [NSURL URLwithString:@"http://www.google.com"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

Simply to check
NSURL *URL = [NSURL URLwithString:@"http://google.com"]; 
NSString *webData= [NSString stringWithContentsOfURL:URL]; 

Upvotes: 1

Related Questions