1

AFNetworking の AFHTTPClient を使用して、IOS アプリから TastyPie で Django を使用しているサーバーに呼び出しを行います。サーバー側で認証をオフにするとうまくいきます。ただし、認証を要求し、適切なユーザー名とパスワードをコードに挿入すると、次の 401 認証エラーが表示されます。

\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 #import "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:mypassword@127.0.0.1:8000/api/v1/shoppinglist"

これに関するヘルプは素晴らしいでしょう。認証情報を静的ベース URL に直接挿入せずに AFHTTPClient を使用できるのは素晴らしいことですが、これは完全に不適切に思えます。前もって感謝します!

4

1 に答える 1

4

これに基づく: https://github.com/AFNetworking/AFNetworking/issues/426

- (void)getPath:(NSString *)path parameters...AFHTTPClient サブクラスのメソッドを次のようにオーバーライドします。

- (void)getPath:(NSString *)path parameters:(NSDictionary *)parameters
    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [operation setAuthenticationChallengeBlock:^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
        NSURLCredential *newCredential = [NSURLCredential credentialWithUser:self.username password:self.password persistence:NSURLCredentialPersistenceForSession];
        [challenge.sender useCredential:newCredential forAuthenticationChallenge:challenge];
    }];
    [self enqueueHTTPRequestOperation:operation];
}

AFHTTPRequestOpertaion に認証チャレンジ ブロックを追加するだけで、残りは元の実装と同じhttps://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFHTTPClient.m

于 2012-10-20T18:58:28.583 に答える