AFNetworking,获得401正确的令牌

时间:2013-10-29 04:58:05

标签: ios rest afnetworking

我正在使用Chrome Rest客户端使用正确的令牌在https://www.ez-point.com/api/v1/ezpoints上发出请求。我正好得到了结果。但是,使用AFNetworking时,我得到的是401。

这是我的代码段:

NSURL *url = [[NSURL alloc] initWithString:@"https://www.ez-point.com/api/v1/"];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url ];
[httpClient setAuthorizationHeaderWithToken:@"xxxxxxxxxx"];

NSMutableURLRequest *request = [httpClient requestWithMethod:@"GET" path:@"/ezpoints" parameters:nil];

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");

这是错误:

2013-10-29 08:51:38.908 EZ-POINT[4944:c07] I restkit:RKLog.m:34 RestKit logging initialized...
2013-10-29 08:51:39.189 EZ-POINT[4944:c07] I restkit.network:RKObjectRequestOperation.m:180 GET 'https://www.ez-point.com/ezpoints'
2013-10-29 08:51:41.908 EZ-POINT[4944:c07] E restkit.network:RKObjectRequestOperation.m:209 GET 'https://www.ez-point.com/ezpoints' (401 Unauthorized) [2.7191 s]: Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 401" UserInfo=0x1052ef40 {AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest https://www.ez-point.com/ezpoints>, NSErrorFailingURLKey=https://www.ez-point.com/ezpoints, NSLocalizedDescription=Expected status code in (200-299), got 401, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xac54520>}
2013-10-29 08:51:41.908 EZ-POINT[4944:c07] Error

1 个答案:

答案 0 :(得分:1)

使用以下代码:

NSURL *url = [[NSURL alloc] initWithString:@"https://www.ez-point.com/api/v1/ezpoints"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setValue:@"4f62fab9c91c46ad971cc2ae4a32bb6f" forHTTPHeaderField:@"Authorization"];
    AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:request
        success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
            NSLog(@"%@",[JSON objectForKey:@"status"]);
        }
            failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                NSLog(@"%@", @"Error");
        }];
    [operation start];