【问题标题】:Afnetworking error using PUT request with Error 400使用带有错误 400 的 PUT 请求的 Afnetworking 错误
【发布时间】:2012-11-28 17:17:16
【问题描述】:

我正在尝试使用 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

请帮忙~~

【问题讨论】:

  • 失败的错误 Domain=com.alamofire.networking.error Code=-1011 “预期状态码在 (200-299),得到 400” UserInfo=0x6b9edd0 {NSErrorFailingURLKey=api.parse.com/1/classes/Shopping/wPHsodI08s, NSLocalizedDescription=Expected (200-299) 中的状态码,得到 400}

标签: ios ios5 increment afnetworking put


【解决方案1】:

默认情况下,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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 2020-05-09
      • 2023-04-08
      • 1970-01-01
      相关资源
      最近更新 更多