0

我真的很难过。我需要将此 cURL 命令转换为objective-c。我正在使用 AFNetworking 库来解决这个问题,但它每次都返回错误的请求(错误 400)。我会很感激帮助。

卷曲命令

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);
}];
4

1 回答 1

1

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

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager 管理器];
[经理 setRequestSerializer:[AFJSONRequestSerializer 序列化器]];
[manager.requestSerializer setValue:@"Bearer XXXXXXXXXXXXX" forHTTPHeaderField:@"Authorization"];

看来,默认情况下,AFHTTPRequestOperationManager使用AFHTTPRequestSerializer,它不会正确格式化 JSON 正文开箱即用。改用AFJSONRequestSerializer子类可以解决此问题。

于 2015-04-21T22:38:22.653 回答