NSURLRequest添加请求头的时候有两个方法
- (void)addValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(NSString *)field;
做项目的时候需要添加特定参数给服务端来获取不同的页面,使用addValue方法第一次请求可以成功获取,第二次失败。查询了官方文档发现:
/*!
@method addValue:forHTTPHeaderField:
@abstract Adds an HTTP header field in the current header
dictionary.
@discussion This method provides a way to add values to header
fields incrementally. If a value was previously set for the given
header field, the given value is appended to the previously-existing
value. The appropriate field delimiter, a comma in the case of HTTP,
is added by the implementation, and should not be added to the given
value by the caller. Note that, in keeping with the HTTP RFC, HTTP
header field names are case-insensitive.
@param value the header field value.
@param field the header field name (case-insensitive).
*/
- (void)addValue:(NSString *)value forHTTPHeaderField:(NSString *)field;```
>意思就是将给定值追加到先前存在的值后面
此方法在重新请求的时候会再次把数据添加到hedaerField中。会导致同样的参数数据有两份,使得服务端会参数获取错误。
/*!
@method setValue:forHTTPHeaderField:
@abstract Sets the value of the given HTTP header field.
@discussion If a value was previously set for the given header
field, that value is replaced with the given value. Note that, in
keeping with the HTTP RFC, HTTP header field names are
case-insensitive.
@param value the header field value.
@param field the header field name (case-insensitive).
*/
- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(NSString *)field;```
类似字典赋值,同样的key、value只会存一份。如果需求是将参数添加到请求头中,应该使用第二个方法。
将坑记录下来。