3

NSURLResponseの応答ヘッダーを変更する必要があります。これは可能ですか?

4

4 に答える 4

9

私はちょうどこれについて友人と話していました。私の提案は、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をサポートできる場合は、代わりにこれをすべてカテゴリに使用して詰め込むこともできます。

于 2010-02-03T19:18:23.593 に答える
3

allHeaderFieldsメソッドを使用して、それらを NSDictionary に読み込むことができます。

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

100% 安全にするには、次のようにラップします。

if ([response respondsToSelector:@selector(allHeaderFields)]) {... }
于 2010-01-19T20:12:44.583 に答える
-2

あなたはそれを行うことができますNSHTTPURLResponse.SwiftNSURLResponseでは、、、または. その結果、期待されるコンテンツ タイプ、MIME タイプ、テキスト エンコーディングなどのメタ データ情報を取得するためにそれを呼び出すことができますが、HTTP プロトコル レスポンスの処理を担当するのは です。したがって、ヘッダーを操作するのはそれです。NSURLResponsehttpftpdata:httpsNSHTTURLResponse

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()
于 2016-05-25T14:50:43.997 に答える