NSURLSessionConfiguration HTTPAdditionalHeaders no

2019-04-28 23:08发布

Authorization header is set in NSURLSessionConfiguration, however it is not attached to NSURLSessionDataTask. Is this a bug in Foundation framework?

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
[configuration setHTTPAdditionalHeaders:@{@"Authorization":@"123"}];

// Initialize session with NSURLSessionConfiguration
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];

[sessionTask resume];

2条回答
乱世女痞
2楼-- · 2019-04-28 23:31

In the NSURLSessionConfiguration document,

An NSURLSession object is designed to handle various aspects of the HTTP protocol for you. As a result, you should not modify the following headers:

Authorization

Connection

Host

WWW-Authenticate

查看更多
狗以群分
3楼-- · 2019-04-28 23:46

I try this in Swift and it works

    var sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
    var xHTTPAdditionalHeaders: [NSObject : AnyObject] = ["X-test":"taly"]
    sessionConfig.HTTPAdditionalHeaders = xHTTPAdditionalHeaders
    let session = NSURLSession(configuration: sessionConfig)

    let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
查看更多
登录 后发表回答