Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle HTTP Header Field name on iOS/OSX

As we know HTTP header names are case insensitive which is specified in RFC2616.

However I found that all popular iOS/OSX framework such as ASIHTTRequest , AFNetworking ,RestKit test whether or not a header field exists using following code.

[[self responseHeaders] objectForKey:@"Keep-Alive"];
[[self responseHeaders] objectForKey:@"Content-Length"];

the responseHeaders is just an NSDictionary. I had thought CFNetwork layer would handle this however no clues found. Maybe this is a convention in real world?

like image 419
Bob Cromwell Avatar asked Jan 28 '26 07:01

Bob Cromwell


1 Answers

Actually, the -[NSHTTPURLResponse allHeaderFields] method returns a case insensitive NSDictionary instance. This has nothing to do with the _CFCapitalizeHeader function which has been removed in recent versions of CFNetwork. Unfortunately its source code is not available anymore.

Here is a simplified call graph of the allHeaderFields method (OS X 10.8.3)

-[NSHTTPURLResponse allHeaderFields] -- Foundation
    CFHTTPMessageCopyAllHeaderFields() -- CFNetwork
        HTTPMessage::copyAllHeaderFields(__CFArray const**)
            MixedDict::copyAsOrdinaryDict(__CFAllocator const*, __CFArray const**) const
                CFDictionaryCreateMutable()

This dictionary is eventually returned as the result of the allHeaderFields method. Here is what the third parameter passed to CFDictionaryCreateMutable looks like:

version = 0
retain = _keyRetain(__CFAllocator const*, void const*) // __ZL10_keyRetainPK13__CFAllocatorPKv
release = _keyRelease(__CFAllocator const*, void const*) // __ZL11_keyReleasePK13__CFAllocatorPKv
copyDescription = _keyCopyDescription(void const*) // __ZL19_keyCopyDescriptionPKv
equal = _keyEqual(void const*, void const*) // __ZL9_keyEqualPKvS0_
hash = _keyHash(void const*) // __ZL8_keyHashPKv

The _keyEqual C++ method eventually calls CFStringCompare with the kCFCompareCaseInsensitive option.

This is why not caring about case sensitivity of NSHTTPURLResponse headers works.

It is very unfortunate that this behavior is not documented, though. Please dupe radar #13715902 asking for documentation.

like image 126
0xced Avatar answered Jan 30 '26 23:01

0xced