获取http请求响应头
一直都是在給服務器端發送請求的時候可能會出現設置頭文件的情況,但這次獲取HTTP 返回的頭文件,著實讓我糾結一番,但最終還是實現了,總結一下。(PS:其實最后方法很簡單,只是分享一下糾結過程)
先看一下使用 AFNetworking3.0是如何獲取數據的。
AFHTTPSessionManager *httpsManager = [AFHTTPSessionManager manager]; httpsManager.requestSerializer = [AFHTTPRequestSerializer serializer]; httpsManager.responseSerializer = [AFHTTPResponseSerializer serializer]; AFSecurityPolicy *security = [AFSecurityPolicy defaultPolicy]; security.allowInvalidCertificates = YES; security.validatesDomainName = NO; httpsManager.securityPolicy = security; [httpsManager POST:ZCFormatURL(@"/paydone") parameters:params progress:^(NSProgress * _Nonnull uploadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { }]; 添加頭文件:? [httpsManager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"os_type"];
? ? ? ? [httpsManager.requestSerializer setValue:[info getNowTime] forHTTPHeaderField:@"time"];
? ? ? ?
分析一下返回的數據
failure 時:
- NSURLSessionDataTask * _Nullable task 和請求有關的一些描述
- NSError * _Nonnull error 網絡請求不通等錯誤描述
success 時: - NSURLSessionDataTask * _Nonnull task 和請求有關的一些描述
- id _Nullable responseObject AFNetworking格式化之后的結果,與AFHTTPSessionManager的responseSerializer相對應
很明顯,我們所要的數據最有可能是在 task 中,所以那就看一下NSURLSessionDataTask類吧,
/** An NSURLSessionDataTask does not provide any additional* functionality over an NSURLSessionTask and its presence is merely* to provide lexical differentiation from download and upload tasks. */ @interface NSURLSessionDataTask : NSURLSessionTask @end發現它僅僅只是繼承自NSURLSessionTask,并沒有自己的屬性方法,好,那就接著看父類NSURLSessionTask
父類屬性倒是不少(太長了,代碼不放這了)。最有可能包含我們所要信息應該就是response屬性了
好,那就接著看NSURLResponse,發現他的屬性方法中沒有能獲取頭文件的。倒是他的子類中有一個屬性挺順眼的。
/*! @method allHeaderFields @abstract Returns a dictionary containing all the HTTP header fields of the receiver. @discussion By examining this header dictionary, clients can see the "raw" header information which was reported to the protocol implementation by the HTTP server. This may be of use to sophisticated or special-purpose HTTP clients. @result A dictionary containing all the HTTP header fields of the receiver. */ @property (readonly, copy) NSDictionary *allHeaderFields;趕緊回去判定一下返回的task.response是不是NSURLResponse的子類
if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {NSLog(@"The return class is subclass %@",NSStringFromClass([NSHTTPURLResponse class])); }else{ NSLog(@"The return class is not subclass %@",NSStringFromClass([NSHTTPURLResponse class])); }打印日志:
2016-01-15 11:29:52.547 demo[535:106586] The return class is subclass NSHTTPURLResponse
果真是,這下就好辦多了,直接強轉,獲取數據就好了
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response; NSDictionary *allHeaders = response.allHeaderFields;轉載于:https://www.cnblogs.com/wanglizhi/p/5711222.html
總結
以上是生活随笔為你收集整理的获取http请求响应头的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电脑不识别u盘怎么回事 “电脑无法检测U
- 下一篇: CMOS怎么设置启动盘 如何设置CMOS