Mutable NSHTTPURLResponse or NSURLResponse

I need to change the response headers in NSURLResponse. Is it possible?

+3
source share
4 answers

I just talked about it with a friend. My suggestion would be to write a subclass of NSURLResponse. Something like that:

@interface MyHTTPURLResponse : NSURLResponse { NSDictionary *myDict; } 
- (void)setAllHeaderFields:(NSDictionary *)dictionary;
@end

@implementation MyHTTPURLResponse
- (NSDictionary *)allHeaderFields { return myDict ?: [super allHeaderFields]; }
- (void)setAllHeaderFields:(NSDictionary *)dict  { if (myDict != dict) { [myDict release]; myDict = [dict retain]; } }
@end

If you are dealing with an object that you have not created, you can try to use object_setClassit to try out the class. However, I do not know if it will add the necessary instance variable. You can also use objc_setAssociatedObjectand use all of this in a category instead, if you can support the new enough SDK.

+9

NSDictionary, allHeaderFields.

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSDictionary *httpResponseHeaderFields = [httpResponse
allHeaderFields];

100% ,

if ([response respondsToSelector:@selector(allHeaderFields)]) {... }
+3

. HTTP-. , url UIWebView -, (.. "Cache-Control" , ). , NSKeyedArchiver HTTP- .

-(id) archiver:(NSKeyedArchiver*) archiver willEncodeObject:(id) object

, NSDictionary, , (.. "Cache-Control" ). , NSKeyedUnarchiver. , unarchiver .

, iOS 5 Apple

-(id)initWithURL:(NSURL*) url statusCode:(NSInteger) statusCode HTTPVersion:(NSString*) HTTPVersion headerFields:(NSDictionary*) headerFields

( ), API NSHTTPURLResponse

+1

, NSHTTPURLResponse not NSURLResponse, Swift NSURLResponse , http, ftp, data:, https. , , ​​ , mime , NSHTTURLResponse HTTP-. , .

, Server .

let url = "https://www.google.com"
    let request = NSMutableURLRequest(URL: NSURL(string: url)!)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

        if let response = response {

            let nsHTTPURLResponse = response as! NSHTTPURLResponse
            var headers = nsHTTPURLResponse.allHeaderFields
            print ("The value of the Server header before is: \(headers["Server"]!)")
            headers["Server"] = "whatever goes here"
            print ("The value of the Server header after is: \(headers["Server"]!)")

        }

        })
        task.resume()
0

Source: https://habr.com/ru/post/1729129/


All Articles