NSURLRequest如何设置HTTP标头?

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

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

我需要为请求设置HTTP标头。在NSURLRequest类的文档中,我没有找到关于HTTP标头的任何信息。我如何设置HTTP头来包含自定义数据?

提问于
用户回答回答于

你需要使用一个NSMutableURLRequest

NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
                                autorelease];

[request setValue:VALUE forHTTPHeaderField:@"Field You Want To Set"];

或者添加一个标题:

[request addValue:VALUE forHTTPHeaderField:@"Field You Want To Set"];
用户回答回答于

Swift

let url: NSURL = NSURL(string: APIBaseURL + "&login=1951&pass=1234")!
var params = ["login":"1951", "pass":"1234"]
request = NSMutableURLRequest(URL:url)
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

扫码关注云+社区

领取腾讯云代金券