【问题标题】:AFNetworking not receiving response dataAFNetworking 未收到响应数据
【发布时间】:2023-04-04 00:33:01
【问题描述】:

我正在使用 AFNetworking 通过发布 json 对象来获取请求。但我收到的是空值。我正在使用以下代码。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

NSDictionary *params = @ {@"email" :user_name, @"password" :pass_word };
[manager GET:HOST_URL parameters:params
      success:^(AFHTTPRequestOperation *operation, id responseObject)
{
    NSLog(@"JSON: %@", responseObject);
    NSDictionary *weather = (NSDictionary *)responseObject;

}
      failure:
 ^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"Error: %@", error);
     NSLog(@"opstr%@",operation.responseString);
 }];

我应该使用什么方法。如果我使用 POST,我会收到错误消息,提示“操作无法完成。(Cocoa 错误 3840。)”(JSON 文本没有以数组或对象开头,并且允许未设置片段的选项。)

当我使用 GET 时,我得到的响应是空的。我不确定我错在哪里。

提前致谢。

【问题讨论】:

    标签: ios json web-services afnetworking


    【解决方案1】:

    这意味着您的请求响应不是有效的 json。您可以更正 Web 服务以返回正确的 json。或删除以下行

    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    

    因为它正在将响应转换为 json。

    要允许片段,请将代码更改为以下

    [manager GET:HOST_URL parameters:params
      success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
     id json = [NSJSONSerialization JSONObjectWithData:responseObject
                                                options:NSJSONReadingAllowFragments
                                                  error:&deserializingError];
    NSLog(@"JSON: %@", responseObject);
    NSDictionary *weather = (NSDictionary *)responseObject;
    
    }
      failure:
     ^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"Error: %@", error);
     NSLog(@"opstr%@",operation.responseString);
    }];
    

    【讨论】:

    • 我需要使用GET还是POST方法。
    • 这取决于您的网络服务。你现在检查回复了吗?我已经编辑了答案以允许 json 响应中的片段。
    • 出现以下错误 -[__NSCFDictionary bytes]: unrecognized selector sent to instance 0x7fb2c35f7460'
    • 您的响应不是正确的 json。可以给我网址吗?
    • url 只有以下数据 {"data":"Hi"}。我在没有传递参数的情况下得到它。但我想要的是我发送的任何内容(用户名和密码)我应该得到相同的。网络服务返回相同。
    猜你喜欢
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 2021-02-18
    相关资源
    最近更新 更多