iOS NSURLRequest 设置 Header

丶阿沐IP属地: 浙江
1字数 216阅读 7,667

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只会存一份。如果需求是将参数添加到请求头中,应该使用第二个方法。

将坑记录下来。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
1人点赞
更多精彩内容,就在简书APP
"小礼物走一走,来简书关注我"
还没有人赞赏,支持一下
丶阿沐努力做好每一个细节优化的处女座。
总资产2共写了1288字获得34个赞共9个粉丝

推荐阅读更多精彩内容