邮递员给出成功响应,而相同的 API 在通过代码调用时抛出错误

Postman gives a success response while the same API throws error when called through code

A​​ POST API 在我的代码中调用它时抛出错误,同时通过邮递员给出成功响应。我使用相同的方法调用其他服务,它们工作得很好。问题出在这个特定的 API 上。这是我用来调用 API 的代码:

-(void)createNSUrlSessionLogin:(NSURL*)URL postDict:(NSDictionary*)dict successBlock:(completionBlock)completionBlock
              failureBlock:(failureBlock)failure
{
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if ([data length] > 0 && error == nil)
    {            
        NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        NSLog(@"result json: %@", jsonArray);
        if (!jsonArray) {
            failure(NO,nil);
        }else
        {
            completionBlock(YES,jsonArray);
        }

    }

    else if ([data length] == 0 && error == nil){
        failure(NO,nil);
    }

    else if (error != nil){
        NSLog(@"Error is %@",[error description]);
        failure(NO,nil);
    }

}];

[postDataTask resume];
}

感谢任何帮助。

对不起,我不能写评论。但我看到,您通过邮递员 content-type: url-encoded 请求,并通过代码 application-json 。如果 API 仅接受 url-encoded 请求,这就是您的答案。

试试这个...

-(void)serverRequestFetchData:(NSMutableURLRequest*)request withCallback:(void (^)(NSArray *, NSError *))aCallback {

NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    dispatch_sync(dispatch_get_main_queue(), ^{
        NSHTTPURLResponse *statusResponse = (NSHTTPURLResponse *)response;
        if (statusResponse.statusCode >= 200 && statusResponse.statusCode < 300) {
            if (data.length > 0 && error == nil) {
                NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                if (aCallback) {
                    aCallback(array, nil);
                }
            } else {
                aCallback(@[], error);
            }
        } else {
            NSString *statusMessage = [NSString stringWithFormat:@"Invalid status response code: %ld", (unsigned long)statusResponse.statusCode];
            NSError *statusError = [[NSError alloc] initWithDomain:@"com.somedomain" code:10001 userInfo:@{NSLocalizedDescriptionKey : NSLocalizedString(statusMessage, nil)}];
            if (aCallback) {
                aCallback(@[], statusError);
            }
        }
    });
}];
[dataTask resume];

}

-(void)myRequest {

NSString *jsonRequest = [NSString stringWithFormat:@"{\"access_token\":\"ACCESS_TOKEN_HERE\"}"];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];

NSString *URLString = [NSString stringWithFormat:@"YOUR_FIRST_URL_STRING"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URLString]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", (int)[requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

[self serverRequestFetchData:request withCallback:^(NSArray *array, NSError *error) {
}];

}