将cURL请求(使用--data-urlencode)转换为AFNetworking GET请求

Dev*_*ang 3 nsurlrequest ios afnetworking

此问题可能与AFNetworking无关,但更多与构建NSURLRequest有关.我正在尝试使用AFNetworking发出下降的GET请求 -

curl -X GET \
  -H "X-Parse-Application-Id: Q82knolRSmsGKKNK13WCvISIReVVoR3yFP3qTF1J" \
  -H "X-Parse-REST-API-Key: iHiN4Hlw835d7aig6vtcTNhPOkNyJpjpvAL2aSoL" \
  -G \
  --data-urlencode 'where={"playerName":"Sean Plott","cheatMode":false}' \
  https://api.parse.com/1/classes/GameScore
Run Code Online (Sandbox Code Playgroud)

这来自parse.com API https://psarse.com/docs/rest#queries-constraints.

但是,我无法弄清楚如何写

[AFHTTPClient getPath:参数:成功:失败:]

对于这个请求.where子句看起来不像字典,但是这个函数只为其参数输入采用字典.

Pau*_*l.s 6

该参数需要NSDictionary将其转换为URL中的键/值对.因此关键很容易,但在将其设置为字典之前,您需要将其转换为JSON ...

NSDictionary *jsonDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                                @"Sean Plott", @"playerName",
                                [NSNumber numberWithBool:NO], @"cheatMode", nil];

NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];

if (!jsonData) {
    NSLog(@"NSJSONSerialization failed %@", error);
}

NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:
                            json, @"where", nil];
Run Code Online (Sandbox Code Playgroud)

如果我们假设您的客户端配置了这样的东西(通常你是子类AFHTTPClient并且可以将这些内容移动到内部

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"https://api.parse.com/"]];
[client setDefaultHeader:@"X-Parse-Application-Id" value:@"Q82knolRSmsGKKNK13WCvISIReVVoR3yFP3qTF1J"];
[client setDefaultHeader:@"X-Parse-REST-API-Key" value:@"iHiN4Hlw835d7aig6vtcTNhPOkNyJpjpvAL2aSoL"];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
Run Code Online (Sandbox Code Playgroud)

然后你应该可以打电话

[client getPath:@"1/classes/GameScore"
     parameters:parameters 
        success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"Success %@", responseObject);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Failed %@", error);
        }];
Run Code Online (Sandbox Code Playgroud)