NSURLResponseの応答ヘッダーを変更する必要があります。これは可能ですか?
4 に答える
私はちょうどこれについて友人と話していました。私の提案は、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をサポートできる場合は、代わりにこれをすべてカテゴリに使用して詰め込むこともできます。
allHeaderFields
メソッドを使用して、それらを NSDictionary に読み込むことができます。
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSDictionary *httpResponseHeaderFields = [httpResponse
allHeaderFields];
100% 安全にするには、次のようにラップします。
if ([response respondsToSelector:@selector(allHeaderFields)]) {... }
あなたはそれを行うことができますNSHTTPURLResponse
.SwiftNSURLResponse
では、、、または. その結果、期待されるコンテンツ タイプ、MIME タイプ、テキスト エンコーディングなどのメタ データ情報を取得するためにそれを呼び出すことができますが、HTTP プロトコル レスポンスの処理を担当するのは です。したがって、ヘッダーを操作するのはそれです。NSURLResponse
http
ftp
data:
https
NSHTTURLResponse
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()