【问题标题】:How to get the source code of a URL如何获取 URL 的源代码
【发布时间】:2012-05-11 11:55:35
【问题描述】:

当我尝试请求此 URL 时无法获取 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。

【问题讨论】:

    标签: ios nsurl nsmutableurlrequest


    【解决方案1】:

    这行得通:

    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;
    

    【讨论】:

    • 抱歉打错了。我已经更新了这个问题。代码中没有语法错误
    • @sanjana Google 正在重定向,让我再多一点。
    【解决方案2】:

    简单版:

    NSURL *TheUrl = [NSURL URLWithString:@"http://google.com"];
    
    NSString *webData = [NSString stringWithContentsOfURL:TheUrl 
                                  encoding:NSASCIIStringEncoding
                                  error:nil];
    
    NSLog(@"%@", webData);
    

    【讨论】:

      【解决方案3】:
      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]; 
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          对于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];
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-07-14
            • 1970-01-01
            • 1970-01-01
            • 2014-11-25
            • 2019-06-12
            • 1970-01-01
            • 1970-01-01
            • 2013-08-10
            相关资源
            最近更新 更多