GTF*_*GTF 6 upload objective-c basic-authentication afnetworking-2
我需要将视频文件从我的应用程序上传到服务器.我试过这样做,[AFHTTPRequestOperationManager post:parameters:success:failure]但遗憾的是不断收到请求超时.现在我想类似的东西创建上传任务,从自动对焦文档.
我阅读等和AF文档有关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];
Run Code Online (Sandbox Code Playgroud)
该myself.credentials对象已设置有正确的用户名和密码.每当此请求触发时,我都会401 unauthorised作为回复.我试过把它NSLog(@"CHALLENGE")放在上面的挑战块中,但它似乎永远不会被调用,所以AFNetworking没有给我一个提供凭据的方法.我知道这在服务器端运行得非常好,因为我已经使用Postman进行了测试.
如何让AFNetworking让我通过此上传任务提供HTTP Basic Auth的凭据?
我不确定 AFNetworking 的情况setSessionDidReceiveAuthenticationChallengeBlock,但只要您有,NSMutableURLRequest您就可以直接在请求对象上设置授权 HTTP 标头:
[request setValue:base64AuthorizationString forHTTPHeaderField:@"Authorization"];
请记住,该值必须是username:password字符串的 Base64 表示形式。
否则,对于会话管理器上的 GET、POST 等请求,您可以在会话管理器使用的请求序列化器上设置凭据。看:
[AFHTTPRequestSerializer setAuthorizationHeaderFieldWithUsername:password:]
[AFHTTPRequestSerializer clearAuthorizationHeader]
| 归档时间: |
|
| 查看次数: |
1236 次 |
| 最近记录: |