AFNetworking 广场 API

AFNetworking Square API

我真的被这个难住了。我需要将此 cURL 命令转换为 objective-c。我正在使用 AFNetworking 库来解决这个问题,但每次都是 returns 错误请求(错误 400)。我将不胜感激。

cURL 命令:

curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer XXXXXXXXXXXXX" -d '{"quantity_delta": -5,"adjustment_type": "SALE"}' https://connect.squareup.com/v1/me/inventory/00CC0141-C50C-4A7A-9FAA-368EC79DA652

AFNetworking Objective-C代码:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:@"Bearer XXXXXXXXXXXXX" forHTTPHeaderField:@"Authorization"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

NSDictionary *parameters = @{@"quantity_delta": [NSNumber numberWithInt:-1], @"adjustment_type": @"SALE"};
NSLog(@"Parameters are %@", parameters);

[manager POST:@"https://connect.squareup.com/v1/me/inventory/00CC0141-C50C-4A7A-9FAA-368EC79DA652" parameters:@{@"quantity_delta": [NSNumber numberWithInt:-1], @"adjustment_type": @"SALE"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

公平警告,我是 AFNetworking 库的新手,但我能够通过在上述示例的前两行之间添加粗体行来成功请求:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
[manager.requestSerializer setValue:@"Bearer XXXXXXXXXXXXX" forHTTPHeaderField:@"Authorization"];

似乎默认情况下,AFHTTPRequestOperationManager 使用 AFHTTPRequestSerializer,它 不是 格式 JSON 开箱即用的正文.使用 AFJSONRequestSerializer 子类可以解决这个问题。