【问题标题】:AFNetworking 2.0 : Cannot POST with JSON from IOSAFNetworking 2.0:无法使用来自 IOS 的 JSON POST
【发布时间】: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


【解决方案1】:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
manager.requestSerializer = serializer;

现在它可以工作了。

【讨论】:

  • 谢谢。完美运行。我已经浪费了将近 5 个小时来调试和检查问题。
【解决方案2】:

我在通过 Swift 使用 AFNetworking API 时遇到了同样的问题,尝试发送一个帖子请求,最后感谢 user1805458 的帖子。

基本上,对于 AFHTTPRequestOperationManager 的 requestSerializer,我也在使用 AFHTTPRequestSerializer,然后尝试将 Content-Type 设置为“Application/JSON”,但它不起作用。

但是一旦我改用 AFJSONRequestSerializer,它现在就可以正常工作了:

        let manager = AFHTTPRequestOperationManager()
        manager.requestSerializer = AFJSONRequestSerializer(writingOptions: nil)

        // Contrary to user1805458's solution, I did not need to use these two instructions below using Swift.
        // manager.requestSerializer.setValue("Application/JSON", forHTTPHeaderField:"Content-Type")
        // manager.requestSerializer.setValue("Application/JSON", forHTTPHeaderField:"Accept")

如果您使用 Swift、AFNetworking 并尝试发送包含 JSON 正文的发布请求,我希望它能帮助您解决此错误。

【讨论】:

    【解决方案3】:

    其实我终于搞定了。

    基本上,对于 AFHTTPRequestOperationManager 的 requestSerializer,我使用的是 AFHTTPRequestSerializer,然后尝试将 Content-Type 设置为“application/json”

    但是一旦我改用 AFJSONRequestSerializer,它现在就可以正常工作了

    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
    
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    operationManagerInstance.requestSerializer = requestSerializer;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多