![](/img/trans.png)
[英]Swift get Last-Modified property from NSHTTPURLResponse as NSDate
[英]How to get HTTP protocol version from a given NSHTTPURLResponse?
從NSHTTPURLResponse
文檔中,我沒有找到獲取HTTP
版本的方法(ie "HTTP/1.1" or "HTTP/1.0")
。
HTTP
頭字段可通過所有Header Fields屬性獲得,但HTTP
協議版本未在頭字段內給出,因為它不是HTTP
頭。
注意: init, NSHTTPURLResponse
初始化程序(initWithURL:statusCode:HTTPVersion:headerFields:)
確實需要HTTPVersion
作為輸入,所以理論上它可能已保存在那里。
但是,我找不到從給定響應中獲取HTTPVersion
的屬性或方法,例如從NSURLSessionDataTask返回的響應。
沒有公開的方法來訪問NSHTTPURLResponse
實例的http版本,響應的版本取決於請求版本。
如果您確實想要訪問http版本,可以使用CFNetworking
。
CFN_EXPORT CFHTTPMessageRef
CFHTTPMessageCreateResponse(
CFAllocatorRef __nullable alloc,
CFIndex statusCode,
CFStringRef __nullable statusDescription,
CFStringRef httpVersion) CF_AVAILABLE(10_1, 2_0);
CFHTTPMessageCopyVersion()
返回HTTP版本。
實際上-[NSHTTPURLResponse initWithURL:(NSURL *)URL statusCode:(NSInteger)statusCode HTTPVersion:(NSString *)version headerFields:(NSDictionary *)fields]
使用CFHTTPMessageCreateResponse
來創建HTTP響應。 見NSURLResponse.m
NSURLResponse
支持_CFURLResponse
結構。
typedef struct _CFURLResponse {
CFRuntimeBase _base;
CFAbsoluteTime creationTime;
CFURLRef url;
CFStringRef mimeType;
int64_t expectedLength;
CFStringRef textEncoding;
CFIndex statusCode;
CFStringRef httpVersion;
CFDictionaryRef headerFields;
Boolean isHTTPResponse;
OSSpinLock parsedHeadersLock;
ParsedHeaders* parsedHeaders;
} _CFURLResponse;
typedef const struct _CFURLResponse* CFURLResponseRef;
您可以在NSURLResponse
實例上使用_CFURLResponse
getter方法獲取此結構:
CFTypeRef test = CFBridgingRetain([response performSelector:NSSelectorFromString(@"_CFURLResponse")]);
CFShow(test);
請不要使用_CFURLResponse
私有API,因為CFNetwork不提供其返回值格式的任何保證。
查詢HTTP版本的推薦方法是實現URLSession:task:didFinishCollectingMetrics:
delegate方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.