设置 NSMutableURLRequest header 和添加一个之间的区别

Difference between setting an NSMutableURLRequest header and adding one

我想知道设置 header 值和向 NSMutableURLRequest 添加 header 值之间的区别是什么。听起来很明显,但是,例如,您不能每次都使用 addValue 吗?设置不存在的 header 会抛出错误吗?如果 header 已存在于请求中,添加它是否会覆盖现有值?

例子

let request.NSMutableURLRequest(URL: NSURL(string: "someURL")!) 
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
...

我觉得苹果官方文档的讨论很清楚:

addValue

This method provides the ability to add values to header fields incrementally. If a value was previously set for the specified field, the supplied value is appended to the existing value using the appropriate field delimiter. In the case of HTTP, the delimiter is a comma.

setValue

The new value for the header field. Any existing value for the field is replaced by the new value.


setValue 替换。 addValue 附加分隔符