在Cocoa中制作HTTP请求模仿浏览器

时间:2011-03-20 21:42:37

标签: objective-c cocoa http macos

因此,我试图阅读HTML文件的内容,以便从特定网站中删除一些元数据。

然而,我遇到的问题是,当我通过Web浏览器或我实现的python调用执行调用时,使用cocoa库调用在objective-c中执行HTTP请求会给我一个不同的HTML文件。

这很烦人的原因是我正在抓取每个请求生成的密钥。该网站似乎知道我何时通过cocoa而不是python库或浏览器执行请求。

任何人都可以对此有所了解吗?

以下是我执行的以下python代码:

self.url = 'http://sample-site.com/1?ax=1ts=123123.12'
request = urllib2.Request(complete_url)
response = urllib2.urlopen(request)
html_data = response.read()

以下是我尝试过的可可尝试:

  1. NSString * completeUrl = [url stringByAppendingFormat:@"//%d?ax=1&ts=%1.2f", pageNumber, time];

  2. 另一次尝试:

        NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:hypeURL] autorelease];
        [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
        NSURLResponse* response = nil;
        NSError* error = nil;
        NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        NSString *hypeHTML = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    
  3. cocoa中的尝试正在检索HTML,但HTML包含我解析的每次刷新生成的键值。使用cocoa执行请求时,键值在每次执行应用程序时都不会改变(相同的键在HTML中),在Python中,HTML正确地为每个请求提供不同的键。

    由于

1 个答案:

答案 0 :(得分:3)

网站可能会检测到用户代理并根据它返回不同的内容 只需更改请求标题中的用户代理:

NSString* userAgent = @"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8) Gecko/20051111 Firefox/1.5 BAVM/1.0.0";
NSURL* url = [NSURL URLWithString:@"http://www.stackoverflow.com/"];
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease];
[request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"%@",result);

使用此代码,服务器认为您在Linux上运行Firefox :)。

获取特定浏览器的当前用户代理/查找用户代理:
http://www.useragentstring.com/

相关问题