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?


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

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

This works fine for me:

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

The User-Agent is set later if you do not provide one yourself, so it is nil when you try to read it.

Why not subclass NSMutableURLRequest, and in the constructor of your subclass, simply set the "User-Agent" HTTPHeaderField. This will have a less pain point of you always remembering to set the header whenever creating an instance.

Need Your Help

What does mysql_esp mean?

php mysql

I encountered a code with following syntax , please help me understand it :

Php Mongodate Converting Date to 1970

php mongodb mongodate

Hello guys I 'm storing date in mongodb. The problem that I'm facing is that the date time string that I get. I try to convert it into mongodate but it converts it to 0.00000000 2016. Here is the c...