在AFNetworking 3.0中使用自定义HTTP标头

时间:2015-12-16 14:32:45

标签: ios swift afnetworking afnetworking-3

我想使用我的http标头If-None-Match,但我没有找到如何使用AFNetworking 3.0

Migration Guide并没有解释任何相关内容,基本上只是说使用a normal GET request这似乎对我没有帮助。

以下是我在AFNetworking 2中所做的事情:

let getAvatarRequest = NSURLRequest(URL: avatarUrl!, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 60).mutableCopy()    
getAvatarRequest.setValue(avatarImageETag!, forHTTPHeaderField: "If-None-Match")

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

好的我找到了答案,实际上没有任何改变,但这并不明显,这是代码:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let manager = AFURLSessionManager(sessionConfiguration: configuration)

let request = NSMutableURLRequest(URL: remoteFileURL!)
request.setValue("", forHTTPHeaderField: "If-None-Match")
let downloadTask = manager.downloadTaskWithRequest(request, progress: nil, destination: { (targetURL: NSURL, response: NSURLResponse) -> NSURL in
    // Success
}, completionHandler: { (response: NSURLResponse, filePath: NSURL?, error: NSError?) -> Void in
    // Error
})
downloadTask.resume()

答案 1 :(得分:0)

警告偏离主题的回答 但在某些情况下,您可以决定使用AFNetworking是不可能的。我的任务是从自定义API下载文件。对于访问,我将在标题中的"x-token"键上使用令牌。 AFNetworking不仅仅适用于下载,在GET / POST请求中一切都很棒!

// we use "x-token" to acces
self.tokenSessionManager = [AFHTTPSessionManager manager];
((AFJSONResponseSerializer *)_tokenSessionManager.responseSerializer).removesKeysWithNullValues = YES;
[_tokenSessionManager.requestSerializer setValue:self.user.token forHTTPHeaderField:@"x-token"];
// it works perfect in other GET/POST requests but not in downloading


 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:item.urlString]];
// try to set it directly in request
NSString *key = @"x-token";
[request setValue:[self.tokenSessionManager.requestSerializer valueForHTTPHeaderField:key] forHTTPHeaderField:key];
[[self.tokenSessionManager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    return [NSURL URLWithString:filePath];
} completionHandler:^(NSURLResponse *response, NSURL *urlPath, NSError *error) {
    NSLog(@"Failure");
}] resume];

您可以尝试使用NSURLSessionNSURLRequest

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSString *key = @"x-token";
sessionConfiguration.HTTPAdditionalHeaders = @{key:[self.tokenSessionManager.requestSerializer valueForHTTPHeaderField:key]};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:item.urlString]];
[[session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    NSLog(@"Success");
}] resume];

答案 2 :(得分:-4)

这来自README

直接在全局请求方法中支持向请求添加自定义HTTP标头。这样可以轻松地将HTTP标头附加到可以不断更改的请求。

  

对于不更改的HTTP标头,建议将其设置为开   NSURLSessionConfiguration因此它们会自动应用于任何   NSURLSessionTask由底层NSURLSession创建。

let headers = [
    "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
    "Content-Type": "application/x-www-form-urlencoded"
]

Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
     .responseJSON { response in
         debugPrint(response)
     }