AFNetworking回复问题:未经授权(401)

时间:2016-11-06 17:27:40

标签: ios objective-c json afnetworking nsurlsession

我在我的项目中使用了AFNetworking,每当我发送请求时,我都会在失败的情况下收到此消息,

  

错误Domain = com.alamofire.error.serialization.response Code = -1011   "请求失败:未授权(401)"   的UserInfo = {com.alamofire.serialization.response.error.response =   com.alamofire.serialization.response.error.data =< 7b227375 63636573   73223a66 616c7365 2c226d65 73736167 65223a22 41757468 656e7469   63617469 6f6e2066 61696c65 64227d>,NSLocalizedDescription = Request   失败:未经授权(401)}

这就是我使用AFNetworking发送请求的方式。

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];

NSString *path = [NSString stringWithFormat:@"/api/##/##/##/sign_in"];

NSString *params = @"{\"user\": {\"uid\": \"10236412002551\",\"access_token\":\"g6tdbvc34seadcx7yufbbcgvf8ijhss\",\"email\": \"user@domain1.com\",\"latitude\": \"6.927079\",        \"longitude\": \"79.861243\",\"remote_avatar_url\": \"\"}}";

manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

AFSecurityPolicy* policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
[policy setValidatesDomainName:NO];
[policy setAllowInvalidCertificates:YES];

[manager POST:path parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
    if([[responseObject objectForKey:@"error_code"] intValue]==0){
        if (success) {
           success(userArray);
        }
     }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

但是如果我能通过使用NSURLSession得到正确的答案。(请参阅下面的代码)

    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

    NSURL * url = [NSURL URLWithString:@"http://##/api/##/##/##/sign_in"];
    NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];

    NSString * params =@"{\"user\": {\"uid\": \"10236412002551\",\"access_token\":\"g6tdbvc34seadcx7yufbbcgvf8ijhss\",\"email\": \"user@domain1.com\",\"latitude\": 6.927079,        \"longitude\": 79.861243,\"remote_avatar_url\": \"\"}}";

    [urlRequest addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
                                                       completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                           NSLog(@"Response:%@ %@\n", response, error);
                                                           if(error == nil)
                                                           {
                                                               NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];

                                                               NSDictionary * json  = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

                                                               NSLog(@"Data = %@",text);
                                                               NSLog(@"Data = %@",json);
                                                           }

                                                       }];
    [dataTask resume];

我对使用AFNetworking感兴趣,但由于这个问题,我无法继续前进。请帮我解决AFNetworking的问题。

这是我应该发送的请求,

{ 
    "user": {
       "uid": "102364120025511",
       "access_token": "g6tdbvc34seadcx7yufbbcgaavf8ijh",
       "email": "user@domain.com",
       "latitude": 6.927079,
       "longitude": 79.861243,
       "remote_avatar_url": ""
    }
}

这是我应该得到的回应,

{
  "success": true,
  "message": "Successfully authenticated",
  "user": {
    "id": 123,
    "email": "user@domain.com",
    "provider": "facebook",
    "latitude": 6.927079,
    "longitude": 79.861243,
    "avatar": {
      "url": "",
      "thumb": ""
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您将params作为JSON字符串提供,然后指示AFNetworking使用AFJSONRequestSerializer然后在JSON结构中表示该字符串。实际效果是你已经两次JSONified。

您应该提供字典对象,让AFNetworking为您创建JSON,例如:

NSString *params = @{@"user": @{@"uid": @"10236412002551", @"access_token": @"g6tdbvc34seadcx7yufbbcgvf8ijhss", @"email": @"user@domain1.com", @"latitude": @6.927079, @"longitude": @79.861243, @"remote_avatar_url": @""}};

顺便说一下,让AFNetworking(使用NSJSONSerialization)为你构建JSON将比你自己尝试这样做更加强大。因此,即使您使用NSURLSession方法,我也建议构建此嵌套字典结构,然后使用NSJSONSerialization构建JSON数据有效负载。或者,如果您使用AFNetworking,它将为您执行此操作。