簡體   English   中英

如何從給定的NSHTTPURLResponse獲取HTTP協議版本?

[英]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方法

https://developer.apple.com/documentation/foundation/nsurlsessiontasktransactionmetrics/1643141-networkprotocolname?language=objc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM