【问题标题】:Use custom HTTP Headers with AFNetworking 3.0在 AFNetworking 3.0 中使用自定义 HTTP 标头
【发布时间】:2015-12-16 14:32:45
【问题描述】:

我想使用我的 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")

感谢您的帮助。

【问题讨论】:

    标签: ios swift afnetworking afnetworking-3


    【解决方案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()
    

    【讨论】:

      【解决方案2】:

      警告题外话 但在某些情况下,您可以决定无法使用 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];
      

      【讨论】:

        【解决方案3】:

        这是来自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)
             }
        

        【讨论】:

        • 是的,好吧......这是 Alamofire,而不是 AFNetworking,即使我很欣赏这个答案,它也完全离题了
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-27
        • 2012-02-24
        • 1970-01-01
        • 2014-07-10
        • 2012-01-17
        • 2012-09-22
        • 2010-10-09
        相关资源
        最近更新 更多