【问题标题】:AFNetworking upload task with credentials (HTTP Basic Auth)带有凭据的 AFNetworking 上传任务(HTTP 基本身份验证)
【发布时间】:2014-09-29 19:25:41
【问题描述】:

我需要将视频文件从我的应用上传到服务器。我尝试通过[AFHTTPRequestOperationManager post:parameters:success:failure] 这样做,但不幸的是不断收到请求超时。我现在正在尝试类似于 Creating an Upload Task from the AF Docs.

我阅读了on SOAF Docs 关于setSessionDidReceiveAuthenticationChallengeBlock: 并尝试实现整个上传问题如下:

__block ApiManager *myself = self;

// Construct the URL
NSString *strUrl = [NSString stringWithFormat:@"%@/%@", defaultUrl, [self getPathForEndpoint:endpoint]];
NSURL *URL = [NSURL URLWithString:strUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

// Build a session manager
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

// Set authentication handler
[manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) {
    *credential = myself.credentials;
    return NSURLSessionAuthChallengeUseCredential;
}];


// Create the upload task
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        [myself endpoint:endpoint returnedFailure:error];
    } else {
        [myself endpoint:endpoint returnedSuccess:responseObject];
    }
}];

// and run with it
[uploadTask resume];

myself.credentials 对象之前已设置为具有正确的用户名和密码。每当此请求触发时,我都会收到 401 unauthorised 作为响应。我尝试将NSLog(@"CHALLENGE") 放在上面的挑战块中,但它似乎从未被调用,因此 AFNetworking 没有给我提供凭据的方法。我知道这在服务器端运行良好,因为我已经使用 Postman 对其进行了测试。

如何让 AFNetworking 让我通过此上传任务为 HTTP 基本身份验证提供凭据?

【问题讨论】:

    标签: objective-c upload afnetworking-2 basic-authentication


    【解决方案1】:

    我不确定 AFNetworking 的 setSessionDidReceiveAuthenticationChallengeBlock,但只要你有一个 NSMutableURLRequest,你就可以直接在请求对象上设置 Authorization HTTP Header:

    [request setValue:base64AuthorizationString forHTTPHeaderField:@"Authorization"];

    请记住,该值必须是 username:password 字符串的 base64 表示形式。

    否则,对于会话管理器上的 GET、POST 等请求,您可以在会话管理器使用的请求序列化程序上设置凭据。见:

    [AFHTTPRequestSerializer setAuthorizationHeaderFieldWithUsername:password:] [AFHTTPRequestSerializer clearAuthorizationHeader]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 2012-09-08
      • 2018-01-24
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      相关资源
      最近更新 更多