【发布时间】:2013-12-21 12:41:48
【问题描述】:
自从升级我的 IOS 代码以使用 AFNetworking 版本 2.0 而不是 1.x 后,我无法再使用 JSON 参数执行 HTTP Post。
我怀疑这是因为我的 HTTP 请求标头不是“application/json”,但我尝试过这样做,但仍然无法正常工作。
这是我尝试通过 JSON POST 的测试代码:
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
email, @"email",
password, @"password",
nil];
[[OTApiClient sharedInstance] POST:@"login" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"result: %@", responseObject);
Boolean response = [[responseObject valueForKey:@"success"] boolValue];
if(response == TRUE) {
//ok, success
NSLog(@"success");
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Successfully logged in" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
} else {
NSLog(@"Not successful");
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"The email or password is incorrect." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
}
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
});
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@ , for operation: %@", error, operation);
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"There is a problem connecting to the server, please try again soon." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
});
}];
});
我不断收到此错误:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0xca80730 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.} , for operation: <AFHTTPRequestOperation: 0xca6bee0, state: isFinished, cancelled: NO request: <NSMutableURLRequest: 0xca76040> { URL: http://1.2.3.4:9000/api/login }, response: <NSHTTPURLResponse: 0xc963d60> { URL: http://1.2.3.4:9000/error404 } { status code: 404, headers {
"Content-Length" = 1809;
"Content-Type" = "text/html; charset=utf-8";
} }>
我非常确定服务器已启动并可访问,因为所有其他 GET 调用都正常工作。
我已经检查了 AFNetworking 2.0 的更新文档,看来我所拥有的是执行 JSON POST 的正确方法
如果我遗漏了什么,请告诉我
谢谢 是
【问题讨论】:
-
你能发布你的 JSON 吗?错误消息中返回的 JSON 内容不是有效的 JSON,所以我想知道这是否是问题所在。
-
为什么 "Content-Type" = "text/html; charset=utf-8";而不是 application/json ?你试过在服务器端解决这个问题吗?
-
尝试创建操作并添加操作。JSONReadingOptions = NSJSONReadingAllowFragments;
-
嗨,Grzegorz,我会试试 JSONReadingOptions 并告诉你。另外,我相信 text/html 是由于服务器端的 404 页面而生成的。对于 mttdbrd,我在上面的示例中发布的 JSON 是 { "email": "some email", "password": "some password" } 我认为它没有问题,因为它是由 AFNetworking 自动生成的NSDictionary 参数
标签: ios json post afnetworking afnetworking-2