如何使用 AFHTTPSessionOperation 或 AFHTTPSessionManager 设置票证?

How to set ticket with AFHTTPSessionOperation or AFHTTPSessionManager?

有人知道如何在 AFHTTPSessionOperation 中设置 ticket 吗? 这是之前使用 AFNetworking 框架 1.0

的调用
NSURLRequest* request = [self.myClient requestWithMethod:@"POST" path:[NSString stringWithFormat:@"%@/%@", controller, action] parameters:parameters];
AFHTTPRequestOperation* operation = [self.myClient HTTPRequestOperationWithRequest:request success:success failure:failure];
[self.mirrorClient enqueueHTTPRequestOperation:operation];

票证存储在self.myClient中。 self.myClient.ticket

但我不确定如何在以下调用中使用 AFHTTPSessionOperation 和 AFNetworking 框架 3.1 来实现它。

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = manager.requestSerializer;
[requestSerializer  setValue:[NSString stringWithFormat:@"%@", self.myClient.ticket] forHTTPHeaderField:@"Authorization"];

NSOperation *operation = [AFHTTPSessionOperation operationWithManager:manager HTTPMethod:@"POST" 
URLString:urlString parameters:parameters 
uploadProgress:nil downloadProgress: nil 
success:success failure:failure];

谢谢

这段代码看起来基本正确。您可以稍微简化 requestSerializer 配置,我可能不会为每个请求实例化一个新的 session,但以下对我来说效果很好:

- (void)performRequest:(NSString *)urlString
            parameters:(id)parameters
               success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
               failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure {

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:self.myClient.ticket forHTTPHeaderField:@"Authorization"];

    NSOperation *operation = [AFHTTPSessionOperation operationWithManager:manager
                                                               HTTPMethod:@"POST"
                                                                URLString:urlString
                                                               parameters:parameters
                                                           uploadProgress:nil
                                                         downloadProgress:nil
                                                                  success:success
                                                                  failure:failure];
    [self.queue addOperation:operation];
}

我在 Charles 观看了它,12345678 票出现在我的请求 header 中,正如预期的那样:

我怀疑您的问题出在其他地方。此代码确实将 Authorization header 设置为 ticket。确保这是设置 ticket 的正确位置。另外,请确保 ticket 是您认为的那样。