2013-01-24 16 views
7

Sto provando a fare una semplice richiesta POST con Form-Data a un'API ma ottengo sempre uno stato 401 in cambio.AFNetworking Post Form-Data

Posso facilmente effettuare la chiamata al di fuori di xcode (in Postman per esempio) con successo, tutto ciò che faccio è POST per l'url con coppie chiave-valore di tipo Form-Data ma in xcode fallisce sempre.

Ecco il mio AFHTTPClient:

@implementation UnpaktAPIClient 

+ (id)sharedInstance { 
    static UnpaktAPIClient *__sharedInstance; 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
     __sharedInstance = [[UnpaktAPIClient alloc] initWithBaseURL:[NSURL URLWithString:UnpaktAPIBaseURLString]]; 
    }); 
    return __sharedInstance; 
} 

- (id)initWithBaseURL:(NSURL *)url { 
    self = [super initWithBaseURL:url]; 
    if (self) { 
     [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; 
     [self setParameterEncoding:AFFormURLParameterEncoding]; 
    } 
    return self; 
} 

- (NSDictionary *)login:(NSDictionary *)credentials { 

    [[UnpaktAPIClient sharedInstance] postPath:@"/api/v1/users/login" 
            parameters:credentials 
             success:^(AFHTTPRequestOperation *operation, id response) { 
              NSLog(@"success"); 
             } 
             failure:^(AFHTTPRequestOperation *operation, NSError *error){ 
              NSLog(@"%@", error); 
             }]; 

    return nil; 
} 

Ho anche tentato di creare una richiesta con un requestOperation:

- (NSDictionary *)login:(NSDictionary *)credentials { 

    NSMutableURLRequest *request = [[UnpaktAPIClient sharedInstance] requestWithMethod:@"POST" path:@"/api/v1/users/login" parameters:credentials]; 

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request 
                         success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) { 
                          NSLog(@"success"); 
                         } 
                         failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id json){ 
                          NSLog(@"%@", error); 
                         }]; 
    [operation start]; 

    return nil; 
} 

ma ottengo lo stesso errore esatto per tutto il tempo: Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 401". Mi aspetto un riscontro JSON, puoi vedere le condizioni di successo nell'immagine allegata. Sospetto che sia qualcosa di molto semplice, ma mi sto tirando fuori i capelli cercando di trovarlo, sono abbastanza nuovo per il networking. Qualsiasi aiuto sarebbe fantastico, grazie. Postman Success

UPDATE

Poiché la richiesta postino ha params vuote e le intestazioni, ho pensato che mi serviva per arrivare al corpo della forma. Cambiare la richiesta a:

- (NSDictionary *)login:(NSDictionary *)credentials { 

    NSURLRequest *request = [self multipartFormRequestWithMethod:@"POST" 
                  path:@"/api/v1/users/login" 
                 parameters:nil 
             constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 

             }]; 
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request 
                         success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) { 
                          NSLog(@"success"); 
                         } 
                         failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id json) { 
                          NSLog(@"%@", error); 
                         }]; 
    [operation start]; 
    return nil; 
} 

Ora mi dà un errore 404, che è quello che mi aspetterei senza una e-mail e una password validi, ho solo bisogno di capire come aggiungere uno al corpo della forma, qualsiasi cosa Provo ad aggiungere mi dà l'errore "richiesta flusso del corpo esaurito".

+0

hai aggiunto il protocollo per il vostro URL, ad esempio http: //? –

+0

Sì, l'URL di errore che viene segnalato è quello corretto su cui dovrei autenticarmi. – hokiewalrus

+1

Potrebbe essere un problema con l'autenticazione HTTP di base. Per l'autenticazione di base, questo funziona per me: NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: @ ""]]; // tmpBase 64 è base64 di credenziali nel formato username: password NSString * authValue = [NSString stringWithFormat: @ "Basic% @", tmpBase64]; [request setValue: authValue forHTTPHeaderField: @ "Authorization"]; –

risposta

8

Got it, scopre che è un po 'prolisso per aggiungere coppie chiave/valore per formare-dati, ma ho realizzato in questo modo:

NSMutableData *email = [[NSMutableData alloc] init]; 
NSMutableData *password = [[NSMutableData alloc] init]; 
[email appendData:[[NSString stringWithFormat:@"[email protected]"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[password appendData:[[NSString stringWithFormat:@"qwerty"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[formData appendPartWithFormData:email name:@"email"]; 
[formData appendPartWithFormData:password name:@"password"];