Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

iphone - Add HTTP Header to NSURLRequest

Is there any way to add HTTP header to NSURLRequest object? I used to add them in NSMutableURLRequest using:

[request addValue:@"PC" forHTTPHeaderField:@"machineName"]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't think you can modify the HTTP Headers of a NSURLRequest. I think you're trying to modify a NSURLRequest object that you didn't initialize?

You could create a mutableCopy of your request and then set the header fields with the following method:

 -(void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field.

After that you can copy the mutable request back onto your NSURLRequest variable.

EDIT: Added example below

/* Create request variable containing our immutable request
 * This could also be a paramter of your method */
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.stackoverflow.com"]];

// Create a mutable copy of the immutable request and add more headers
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[mutableRequest addValue:@"Hless" forHTTPHeaderField:@"X-user-nick"];

// Now set our request variable with an (immutable) copy of the altered request
request = [mutableRequest copy];

// Log the output to make sure our new headers are there    
NSLog(@"%@", request.allHTTPHeaderFields);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...