Mutable NSHTTPURLResponse或NSURLResponse
您可以使用allHeaderFields
方法将它们读入NSDictionary。
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSDictionary *httpResponseHeaderFields = [httpResponse
allHeaderFields];
是100%安全的,你不会想和
if ([response respondsToSelector:@selector(allHeaderFields)]) {... }
这不是返回一个NSDictionary而不是一个NSMutableDictionary? – 2010-01-19 20:15:20
是的,这就是代码示例中的内容。以下是课程参考资料http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPURLResponse_Class/Reference/Reference.html#//apple_ref/occ/instm/NSHTTPURLResponse/allHeaderFields – shawnwall 2010-01-19 20:30:03
I don看不到不可改变的字典将如何帮助我修改键/值 – 2010-01-19 20:34:46
我只是说这与一个朋友把它包起来。我的建议是写一个NSURLResponse的子类。沿着这些路线的东西:
@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
如果你正在处理一个对象,你没有做,你可以尝试使用object_setClass
到调酒类的。但是我不知道这是否会添加必要的实例变量。你也可以使用objc_setAssociatedObject
,如果你能支持一个足够新的SDK,那么你可以把它全部放在一个类别中。
我有一个类似的问题。我想修改http url响应的头文件。我需要它,因为我想为UIWebView提供缓存的url响应,并且想欺骗Web视图,即响应未过期(即,我想更改标题的“Cache-Control”属性,但保留标题的其余部分)。我的解决方案是使用NSKeyedArchiver对原始http响应进行编码,并使用委托拦截序列化。在
-(id) archiver:(NSKeyedArchiver*) archiver willEncodeObject:(id) object
我检查,如果对象是NSDictionary中,如果是,我回来改性字典(即更新为“缓存控制”报头)。之后我使用NSKeyedUnarchiver对序列化的响应进行反序列化。当然,您可以挂钩到解析器并修改其委托中的标题。
注意,在iOS 5中苹果公司已经加入
-(id)initWithURL:(NSURL*) url statusCode:(NSInteger) statusCode HTTPVersion:(NSString*) HTTPVersion headerFields:(NSDictionary*) headerFields
这是不是在文档(文档错误),但它是NSHTTPURLResponse
的公共API中
你能做到这一点,你'd需要NSHTTPURLResponse
而不是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()
您是否尝试修改从服务器获取的标头?你的意思是NSURLRequest? – notnoop 2010-01-19 20:09:44
wait ... no ..我的意思是NSURLResponse – 2010-01-19 20:26:38