1

我正在尝试使用 PUT 请求增加 Parse 上的数据。

-(void)requestHit {

AFHTTPClient *client = [[AFHTTPClient alloc]initWithBaseURL:[NSURL     URLWithString:kHBFParseAPIBaseURLString]];
[client setDefaultHeader:@"X-Parse-Application-Id" value:kHBFParseAPIApplicationId];
[client setDefaultHeader:@"X-Parse-REST-API-Key" value:kHBFParseAPIKey];

[client registerHTTPOperationClass:[AFJSONRequestOperation class]];

NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                @"Increment",@"__op", [NSNumber numberWithInt:100],@"amount",
                               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 * params = [[NSDictionary alloc]initWithObjectsAndKeys: json, @"hot", nil];


[client putPath:self.shopping.objectId parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
    NSLog(@"Success %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Failed %@", error);
}];
}

我收到错误代码 400。我知道 400 表示 URL 错误,但我在 safari 上检查了 URL,并且能够访问该网站。我在想也许字典编码错误但不知道。这是 Parse 网站上增量的 REST API cURL:

curl -X PUT \
-H "X-Parse-Application-Id: DWZFxindnjGtp3SCMmA4iGaYN55dgVDRmobt7mkC" \
-H "X-Parse-REST-API-Key: QbjhRMhVshPkJmEoDdpS3xAkNOofzLsUBlMBQETU" \
-H "Content-Type: application/json" \
-d '{"score":{"__op":"Increment","amount":1}}' \
https://api.parse.com/1/classes/GameScore/Ed1nuqPvcm

请帮忙~~

4

2 回答 2

0

默认情况下,AFHTTPClient 将使用 AFFormURLParameterEncoding 作为编码参数的方式,因此您必须将其设置为 AFJSONParameterEncoding

https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFHTTPClient.m#L473

https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ#how-do-i-send-json-parameters-in-my-request

于 2013-07-18T18:06:28.857 回答
0

有些java web服务器不能接收@"__op":@(1)这种参数,你应该手动转换成@"0"或者@"1",这样可以避免400错误。去尝试一下。

于 2016-08-07T10:11:00.820 回答