Provide HTTPVersion to NSHTTPURLResponse

1k Views Asked by At

My application uses custom NSURLProtocol subclass. I need to substitute NSHTTPURLResponse with my copy, modifying some of the headers fields. So, I create new NSHTTPURLResponse instance, like that:

@implementation NSHTTPURLResponse (CocoaFix)

- (instancetype)HTTPResponseByRemovingValueForHeaderFields:(NSArray *)fields {
    NSMutableDictionary *mutableHeaderFields = [self.allHeaderFields mutableCopy];
    [mutableHeaderFields removeObjectsForKeys:fields];
    return [[[self class] alloc] initWithURL:self.URL
                                  statusCode:self.statusCode
                                 HTTPVersion:@"HTTP/1.1" // What should I pass here?
                                headerFields:mutableHeaderFields];
}

@end

Problem occurs with HTTPVersion parameter. I didn't find any way to obtain this value from original response.

Documentation says:

This is typically represented as "HTTP/1.1".

But providing hardcoded value not looks like a solution, that will work correctly all the time.

Please, help me with this one.

3

There are 3 best solutions below

4
fullofsquirrels On

Per this answer: NSURLRequest http protocol version, you probably need to at least bridge to the CFNetwork APIs to do this.

0
dgatwood On

Per the CFNetwork team, at least as of a year ago, there was no practical way to obtain that information. In fact, from looking at the runtime analysis of the headers, I doubt that it even gets stored anymore.

If I'm right, then it also has no effect on the networking stack's behavior from that point onwards, so you could say it was "HTTP/999.99" and it wouldn't matter.

0
Nikita On

The NSURLSessionTaskTransactionMetrics class has property named networkProtocolName. This class instance is one of the elements of the array which is also a property named transactionMetrics, which is member of the NSURLSessionTaskMetrics which is input param named metrics in the callback method named ..didFinishCollectingMetrics:.. which is part of the NSURLSessionTaskDelegate protocol.

e.g:

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0)) {
    self.redirectCount = metrics.redirectCount;
    self.networkProtocolName = metrics.transactionMetrics.lastObject.networkProtocolName;
}