向NSURLRequest添加HTTP报头

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (68)

有没有办法将HTTP头添加到NSURLRequest反对?我以前常把它们加进去NSMutableURLRequest使用:

[request addValue:@"PC" forHTTPHeaderField:@"machineName"]
提问于
用户回答回答于

可以创建一个mutableCopy,然后使用以下方法设置标头字段:

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

在那之后你可以copy可变请求返回到您的NSURLRequest变量。

/* 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);
用户回答回答于
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setValue:@"es" forHTTPHeaderField:@"Accept-Language"];

扫码关注云+社区

领取腾讯云代金券