我正在使用来自AFNetworking的AFHTTPClient从我的iOS应用程序调用我的服务器,这是使用Django与TastyPie。当我在服务器端关闭身份验证时它工作得很好;然而,当我需要验证,并插入正确的用户名和密码,我的代码,我将收到下面的401身份验证错误:401错误 - 使用AFNetworking的基本身份验证AFHTTPClient&Tastypie
\2012-09-16 00:24:37.877 RESTtest[76909:f803]
Complex AF: Error Domain=AFNetworkingErrorDomain Code=-1011
"Expected status code in (200-299), got 401"
UserInfo=0x686ba00 {AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x686f130>,
NSErrorFailingURLKey=http://127.0.0.1:8000/api/v1/shoppinglist,
NSLocalizedDescription=Expected status code in (200-299), got 401,
AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest http://127.0.0.1:8000/api/v1/shoppinglist>}
这里是我的代码:
AFAPIClient.h #进口“AFHTTPClient .H”
@interface AFAPIClient : AFHTTPClient
-(void)setUsername:(NSString *)username andPassword:(NSString *)password;
+ (AFAPIClient *)sharedClient;
@end
AFAPIClient.m:
#import "AFAPIClient.h"
#import "AFJSONRequestOperation.h"
static NSString * const baseURL = @"http://@127.0.0.1:8000/api/v1";
@implementation AFAPIClient
+ (AFAPIClient *)sharedClient {
static AFAPIClient *_sharedClient = nil;
static dispatch_once_t pred;
dispatch_once(&pred, ^{
_sharedClient = [[AFAPIClient alloc] initWithBaseURL:[NSURL URLWithString:baseURL]];
//[_sharedClient setAuthorizationHeaderWithUsername:@"myusername" password:@"mypassword"]; I tried putting the authorization command here
});
return _sharedClient;
};
#pragma mark - Methods
-(void)setUsername:(NSString *)username andPassword:(NSString *)password;
{
[self clearAuthorizationHeader];
[self setAuthorizationHeaderWithUsername:username password:password];
}
- (id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setParameterEncoding:AFJSONParameterEncoding];
//[self setAuthorizationHeaderWithUsername:@"myusername" password:@"mypassword"]; I also tried putting the authorization command here
// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:@"Accept" value:@"application/json"];
return self;
}
@end
TQViewController.h:
[...]
- (IBAction)sendAFClientRequest:(id)sender {
//[[AFAPIClient sharedClient] setUsername:@"myusername" andPassword:@"mypassword"];
[[AFAPIClient sharedClient] getPath:@"shoppinglist" parameters:nil success:^(AFHTTPRequestOperation *operation, id response) {
NSLog(@"Complex AF: %@", [response valueForKeyPath:@"objects"]);
} failure:^(AFHTTPRequestOperation *operation, id response) {
NSLog(@"Complex AF: %@", response);
}
];
}
[...]
我知道这是不是我的服务器或我的用户名/密码有问题,我可以通过将用户名/密码进入URL验证就好:
@"http://myusername:[email protected]:8000/api/v1/shoppinglist"
对此的任何帮助将是伟大的。能够在不将认证信息直接插入到静态基本URL的情况下使用AFHTTPClient将是一件好事,这看起来完全不合适。提前致谢!