Question

Is it possible to modify a header on a NSHTTPURLResponse without using the method

initWithURL:statusCode:HTTPVersion:headerFields:

to create a new customized NSHTTPURLResponse

Was it helpful?

Solution

The response object returns an NSDictionary called allHeaderFields. It'd be ideal if you could modify that dictionary directly, but it's not an NSMutableDictionary. Which means that you can only do one of two things:

  • Create a mutable copy of the current allHeaderFields dictionary, and use that in a new NSHTTPURLResponse (I know you said you didn't want to create a new NSHTTPURLResponse, but it's the simplest solution, you grab the other values from the original response, make an NSMutableDictionary that's initialized with the values of the original allHeaderFields, edit the field(s) you need to for whatever you're spoofing, and plug that into the new response.)

  • Otherwise, you could implement a custom subclass of NSHTTPURLResponse that can modify the allHeaderFields object. Great answer that details the basics of how to do that here, however it seems a bit more roundabout. Would only use this if you need to override an awful lot of HTTP Header fields.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top