4

通常http用户代理是这样的:

Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341

如果我

NSMutableURLRequest *newUserAgentRequest = (NSMutableURLRequest*)[NSURLRequest requestWithURL:self.url];
    NSString *userAgent = [newUserAgentRequest valueForHTTPHeaderField:@"User-Agent"];

userAgent 为 nil 或为空表示

NSMutableURLRequest *newUserAgentRequest = (NSMutableURLRequest*)[NSURLRequest requestWithURL:self.url];

没有用户代理,如何使用用户代理发起请求?

4

4 回答 4

7

我只做了如下。这适用于 iOS 设备:

NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] 
                                       initWithURL:[NSURL URLWithString:[yourURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
NSString *userAgent = [NSString stringWithFormat:@"%@ %@",[UIDevice currentDevice].systemName,[UIDevice currentDevice].systemVersion];
[urlRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"];

希望能帮助到你

于 2012-06-28T07:49:15.720 回答
1

设置User_Agent(带下划线)字段适用于某些网站,但不是所有网站,并且通常不会被 NSURL... 类覆盖。除了弄乱字典(我认为这是不允许的,但无论如何我会发布一个示例)之外,另一种选择是方法调配。

+ (void)initialize {
    // Set user agent (the only problem is that we can't modify the User-Agent later in the program)
    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:@"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341", @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
    //only under MRC do we release [dictionnary release];
}
于 2012-06-28T07:40:39.407 回答
1

这对我来说很好:

NSString *userAgent = @"My user agent";
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:9000"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:userAgent forHTTPHeaderField:@"User-Agent"];

如果您自己不提供 User-Agent,则稍后设置,因此nil当您尝试阅读它时。

于 2012-06-28T07:52:31.357 回答
1

为什么不继承 NSMutableURLRequest,在你的子类的构造函数中,简单地设置“User-Agent”HTTPHeaderField。这将减少您在创建实例时始终记住设置标头的痛苦点。

于 2012-12-28T15:21:20.363 回答