在 AFNetworking 3.0 中使用自定义 HTTP Headers
Use custom HTTP Headers with AFNetworking 3.0
我想使用我的 http header If-None-Match
但我不知道如何使用 AFNetworking 3.0
Migration Guide doesn't explain anything about that and basically just say to use a normal GET
request 似乎对我没有帮助。
这是我使用 AFNetworking 2 所做的事情:
let getAvatarRequest = NSURLRequest(URL: avatarUrl!, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 60).mutableCopy()
getAvatarRequest.setValue(avatarImageETag!, forHTTPHeaderField: "If-None-Match")
感谢您的帮助。
本文来自README:
在全局请求方法中直接支持向请求添加自定义 HTTP header。这使得将 HTTP headers 附加到可以不断变化的请求变得容易。
For HTTP headers that do not change, it is recommended to set them on
the NSURLSessionConfiguration so they are automatically applied to any
NSURLSessionTask created by the underlying 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)
}
好的,我找到了答案,实际上没有任何改变,但并不明显,这是代码:
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()
警告off-topic回答
但在某些情况下,您可以决定无法使用 AFNetworking。我的任务只是从自定义 API 下载文件。对于访问,我将在 headers 中的 "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];
您可以尝试使用 NSURLSession
和 NSURLRequest
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];
我想使用我的 http header If-None-Match
但我不知道如何使用 AFNetworking 3.0
Migration Guide doesn't explain anything about that and basically just say to use a normal GET
request 似乎对我没有帮助。
这是我使用 AFNetworking 2 所做的事情:
let getAvatarRequest = NSURLRequest(URL: avatarUrl!, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 60).mutableCopy()
getAvatarRequest.setValue(avatarImageETag!, forHTTPHeaderField: "If-None-Match")
感谢您的帮助。
本文来自README:
在全局请求方法中直接支持向请求添加自定义 HTTP header。这使得将 HTTP headers 附加到可以不断变化的请求变得容易。
For HTTP headers that do not change, it is recommended to set them on the NSURLSessionConfiguration so they are automatically applied to any NSURLSessionTask created by the underlying 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)
}
好的,我找到了答案,实际上没有任何改变,但并不明显,这是代码:
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()
警告off-topic回答
但在某些情况下,您可以决定无法使用 AFNetworking。我的任务只是从自定义 API 下载文件。对于访问,我将在 headers 中的 "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];
您可以尝试使用 NSURLSession
和 NSURLRequest
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];