使用带有错误400的PUT请求的Afnetworking错误

时间:2012-11-28 17:17:16

标签: ios ios5 increment afnetworking put

我正在尝试使用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意味着错误的网址,但我检查了safari上的网址,并且我能够访问该网站。我在想,也许字典的编码方式不对,但却没有任何线索。以下是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

请帮忙~~

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

某些java web服务器无法接收@" __ op":@(1)这种类型的参数,你应该手动将其转换为@" 0"或@" 1",这将避免400错误。试试吧。