AFNetworking 2.0和HTTP基本authentication

在AFNetworking 2.0上找不到AFHTTPClient,使用:

AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://examplewebsite.com]]; [client setAuthorizationHeaderWithUsername:@"username" password:@"password"]; 

如何在AFNetworking 2.0上pipe理?

AFNetworking 2.0新架构使用序列化器来创build请求和parsing响应。 为了设置授权头,您应该首先初始化一个请求操作pipe理器来replaceAFHTTPClient,创build一个序列化器,然后调用专用的方法来设置头。

例如你的代码会变成:

 AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://examplewebsite.com"]]; manager.requestSerializer = [AFHTTPRequestSerializer serializer]; [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"userName" password:@"password"]; 

您应该阅读文档和迁移指南,以了解AFNetworking 2.0版本的新概念。

以下是使用NSURLCredential与AFNetworking 2.0执行基本HTTP身份validation的示例。 这种方法相对于使用AFHTTPRequestSerializer setAuthorizationHeaderFieldWithUsername:password:方法的优点是,您可以通过更改NSURLCredential的persistence:参数来自动将用户名和密码存储在keychain中。 (看到这个答案 )

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; NSURLCredential *credential = [NSURLCredential credentialWithUser:@"user" password:@"passwd" persistence:NSURLCredentialPersistenceNone]; NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"GET" URLString:@"https://httpbin.org/basic-auth/user/passwd" parameters:nil]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [operation setCredential:credential]; [operation setResponseSerializer:[AFJSONResponseSerializer alloc]]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"Success: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Failure: %@", error); }]; [manager.operationQueue addOperation:operation]; 

正如@gimenete提到的那样,在使用@titaniumdecoy凭证方法时,多部分请求会失败,因为这在challenge块中被应用,AFNetworking的当前版本对此有一个问题。 而不是使用凭证方法,您可以将身份validationembedded到NSMutableRequest标头中

  NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"PUT" URLString:path parameters:myParams constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) { [formData appendPartWithFileData:imageData name:imageName fileName:imageName mimeType:@"image/jpeg"]; } error:&error]; NSString *authStr = [NSString stringWithFormat:@"%@:%@", [self username], [self password]]; NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding]; NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]]; [request setValue:authValue forHTTPHeaderField:@"Authorization"]; 

在哪里你需要使用第三方BASE64编码库,例如NSData + Base64.h和.m文件,来自Matt Gallaghers提出的ARC BASE64解决scheme