如何获取URL的源代码

时间:2012-05-11 11:55:36

标签: ios nsurl nsmutableurlrequest

当我尝试请求此网址时,我无法获取HTML源代码: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]);

数据始终为NULL。

5 个答案:

答案 0 :(得分:6)

这有效:

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

但是如果你需要使用NSURLConnection,你应该异步使用它并实现willSendRequest方法来处理重定向。

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

答案 1 :(得分:3)

简单版本:

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

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

NSLog(@"%@", webData);

答案 2 :(得分:1)

You can get the data in following ways :-

1.使用NSUrlConnection作为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]; 

答案 3 :(得分:1)

使用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);
        });
    });
}

然后

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

答案 4 :(得分:0)

对于HTML源代码的异步提取,我建议您使用AFNetworking

1)然后继承AFHTTPCLient子类,例如:

//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)请求异步HTML源代码,将此代码放在任何相关部分

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];
相关问题