Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initial a NSURLRequest with user agent

Usually the http user-agent is like:

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

If I

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

the userAgent is nil or empty means

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

no user-agent includes, how to initial a request with user agent?

like image 907
Jason Zhao Avatar asked Dec 26 '22 22:12

Jason Zhao


2 Answers

I have only done it like the following. This is for iOS devices:

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"];

Hope it helps

like image 193
Eren Beşel Avatar answered Jan 12 '23 14:01

Eren Beşel


Setting the User_Agent (with an underscore) field works for some, but not all websites, and isn't usually overridden by the NSURL... classes. The other alternative, besides messing with the dictionary (which I believe is not allowed, but I'll post an example anyhow), is method swizzling.

+ (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];
}
like image 26
CodaFi Avatar answered Jan 12 '23 14:01

CodaFi