一直都是在給服務器端發送請求的時候可能會出現設置頭文件的情況,但這次獲取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) {
}];
分析一下返回的數據
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屬性了
@property (nullable, readonly, copy) NSURLResponse *response; /* may be nil if no response has been received */
好,那就接著看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;
最終方法就是這么這么的簡單,糾結了好大會,但最終還是有點收獲,記錄一下。。。
最近在讀 大冰 的《乖,摸摸頭》,用里面的一句話來結尾。
源靜則流清 本固則豐茂