将HTTP标头添加到NSURLRequest [英] Add HTTP Header to NSURLRequest

查看:100
本文介绍了将HTTP标头添加到NSURLRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将HTTP标头添加到 NSURLRequest 对象?我曾经在 NSMutableURLRequest 中添加它们:

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

[request addValue:@"PC" forHTTPHeaderField:@"machineName"]


推荐答案

我认为你不能修改 NSURLRequest 的HTTP标头。我想你正在尝试修改你没有初始化的 NSURLRequest 对象?

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?

你可以创建一个您的请求的 mutableCopy 然后使用以下方法设置标题字段:

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.

之后你可以复制可变请求返回 NSURLRequest 变量。

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

编辑:添加以下示例

/* 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);

这篇关于将HTTP标头添加到NSURLRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆