Jason Zhao
Jason Zhao

Reputation: 1288

How to initial a NSURLRequest with user agent

A typical User-Agent for an iPhone looks 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

However, if I do

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

the User-Agent is `nil.

How do I intialize a request with a custom User-Agent?

Upvotes: 5

Views: 10945

Answers (4)

rishabh
rishabh

Reputation: 1165

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.

Upvotes: 1

CodaFi
CodaFi

Reputation: 43330

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

Upvotes: 1

Tammo Freese
Tammo Freese

Reputation: 10754

This works fine for me:

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

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

Upvotes: 2

Eren Beşel
Eren Beşel

Reputation: 1057

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

Upvotes: 8

Related Questions