AFNetworking http基本身份验证会出错"您的API密钥格式不正确"

时间:2016-05-01 00:32:26

标签: ios objective-c httprequest afnetworking http-basic-authentication

尝试使用postmates api,但遇到授权问题。

引用他们的网站:

  

AUTHENTICATION

     

Postmates API需要通过HTTP Basic Auth标头进行身份验证。   您的API密钥应作为用户名包含在内。密码应该   留空。

     

使用的实际标头将是base64编码的字符串   这样:

     

Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==

我尝试使用像这样的AFNetworking

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

NSURLCredential *credential = [NSURLCredential credentialWithUser:@"(my postmates key)" password:@"" persistence:NSURLCredentialPersistenceNone];

NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"GET" URLString:@"https://api.postmates.com/v1/delivery_zones" 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];    

我收到的错误消息是

   Incorrect NSStringEncoding value 0x0000 detected. Assuming NSASCIIStringEncoding. Will stop this compatiblity mapping behavior in the near future.

 Success: {
        code = "invalid_authorization_header";
        kind = error;
        message = "Your API key was not formatted properly";
    }

1 个答案:

答案 0 :(得分:3)

您可能想尝试:

,而不是创建凭证
[request setValue:@"Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==" forHTTPHeaderField:@"Authorization"];