【问题标题】:Getting JSON null from with AFNetworking使用 AFNetworking 获取 JSON null
【发布时间】:2012-06-21 19:20:24
【问题描述】:

我写的两个代码都是一样的

  1. 使用 NSURLConnection 和
  2. 使用 AFNetworking。

我的 NSURLConnection 代码可以正常工作,但 AFNetworking 代码不能。问题是我从我的NSURLConnection 代码收到 JSON 响应,但我没有从AFNetworking 代码收到JSON 响应,但我收到的响应代码为 200。我已经尝试了所有可能的组合,但仍然没有运气。我不知道是什么问题。我想继续使用AFNetworking,所以请有人帮助我。谢谢,--阿米特

NSURLConnection:

- (IBAction)connectHandler:(UIButton *)sender {

//This is where we attempt to connect to the URL represented by self.labelHostURL
//along with exception handling
NSString *request_type = @"STARTUP";    
NSString *request_data = @"{\"lstCacheRefDt\":\"10/10/2010\",\"langCd\":\"en_US\",\"timeZn\":\"America/Chicago\",\"brndId\":\"WM\",\"prgmId\":\"WM0012\"}";
NSLog(@"Request: %@", request_data);

NSURL *url = [NSURL URLWithString:[ self.labelHostURL text ]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
//NSData *requestData = [NSData dataWithBytes:[request_data UTF8String] length:[jsonRequest length]];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

NSString* request_body = [NSString
                          stringWithFormat:@"request_type=%@&request_data=%@",
                          [request_type stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                          [request_data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:[request_body dataUsingEncoding:NSUTF8StringEncoding]];

[NSURLConnection connectionWithRequest:request delegate:self];    }

AFNetworking:

- (void) getHomeData {

NSURL *url = [[NSURL alloc] initWithString:@"https://localhost:8443/MNMMLMockService/mAccountsWeb/services/mnapp/rpc"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSDictionary *homePostParams1 = [NSDictionary dictionaryWithObjectsAndKeys:
                                @"10/10/2010", @"lstCacheRefDt",
                                @"en_US", @"langCd",
                                @"America/Chicago", @"timeZn",
                                @"WM", @"brndId",
                                @"WM0012", @"prgmId", nil];

NSDictionary *homePostParams = [NSDictionary dictionaryWithObjectsAndKeys:@"STARTUP", @"request_type", homePostParams1,@"request_data", nil];

NSLog(@"Dic: %@", homePostParams);

NSMutableURLRequest *homeRequest = [httpClient requestWithMethod:@"POST" path:@"" parameters:homePostParams];
[homeRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[homeRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:homeRequest
                                     success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                                         NSLog(@"JSON %@", JSON);
                                         NSLog(@"operation StatusCode: %d", [response statusCode]);
                                     } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                                         NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
                                     }];
[operation start]; }

【问题讨论】:

    标签: objective-c ios nsurlconnection afnetworking


    【解决方案1】:

    我使用 AFNetworking 库,但您似乎缺少我所做的一些步骤。我通常继承 AFHTTPClient。不管你有没有子类,一定要调用 AFHTTPClient 的 registerHTTPOperationClass 方法。

    例如在初始化过程中我的 AFHTTPClient 子类中,我这样做(其中 self 是 AFHTTPClient 实例):

    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
    

    这将为您设置适当的接受标头。

    对于操作(所有期望 json 响应),我会执行以下操作:

    AFHTTPRequestOperation *httpOperation = [httpClient HTTPRequestOperationWithRequest:request 
        success:^(AFHTTPRequestOperation *operation, id responseJSONObject) { // some logic}
        failure:^(AFHTTPRequestOperation *operation, NSError *error) { // some logic }];
    

    【讨论】:

      【解决方案2】:

      我不明白您为什么要将 url 形式的编码数据而不是 JSON 发送到服务器,但希望返回 JSON。不要设置标题字段。删除这个:

      [homeRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
      [homeRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
      

      如果您想设置它(尽管您不应该这样做),您可以使用AFHTTPClient 进行设置。例如:

      [httpClient setParameterEncoding:AFJSONParameterEncoding];
      

      此外,您知道AFNetworking 会为您编码/解码 JSON,对吧?您将对象传递给它,它会自动将其编码为 JSON,同样会自动接收接收到的 JSON 并将其解码为 Objective-c 对象。所以你永远不会从AFNetworking库收到纯JSON,你会收到相应的对象。

      编辑

      我现在看到了你的问题。您期望 AFNetworking 以 url 形式对一半参数进行编码,但也对另一部分进行 JSON 编码。使用AFNetworking,您必须将整个参数对象编码为一物或另一物。我建议您更改为 100% JSON,方法是保留您创建的 homePostParams 并使用 JSON 对其进行编码,然后重写服务器以期望所有 JSON。

      如果您必须这样拆分,则不能依赖AFNetworking 为您进行编码/解码。你必须做你对NSURLConnection所做的事情:

      NSString *request_data = @"{\"lstCacheRefDt\":\"10/10/2010\",\"langCd\":\"en_US\",\"timeZn\":\"America/Chicago\",\"brndId\":\"WM\",\"prgmId\":\"WM0012\"}";
      NSDictionary *homePostParams = [NSDictionary dictionaryWithObjectsAndKeys:@"STARTUP", @"request_type", request_data,@"request_data", nil];
      

      虽然有点违背AFNetworking 的目的。如果服务器只期望接收 JSON 而不是 url 格式编码会更好

      【讨论】:

      • 感谢您的回复,但没有运气。
      • @AmitVyawahare 查看我的编辑。您是否期待原始 JSON,但得到一个对象?
      • @AmitVyawahare 我现在明白您为什么要进行表单编码,我可以建议您使用 100% JSON 代替表单编码。问题在于 AFNetworking 要么将整个 homePostParams 编码为 JSON,要么不编码。您期望它是一半形式编码和一半 JSON 编码。因此,如果您希望服务器接收任何 JSON,要么它必须是 100% JSON,要么您必须使用与上述非常相似的编码方案,但这几乎违背了AFNetworking 的目的
      • 我收到此编辑错误。 as Error Domain=com.alamofire.networking.error Code=-1016 "预期内容类型 {( "text/json", "application/json", "text/javascript" )},
      • AFJSONRequestOperation 可能需要其中一种内容类型。或者您可以尝试将内容类型设置为 url 形式编码。像[httpClient setParameterEncoding:AFFormURLParameterEncoding]; 这样的东西。它可能会起作用,但如果您使用AFJSONRequestOperation,您会非常期待发送和接收 JSON。
      猜你喜欢
      • 2013-01-20
      • 2015-01-30
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多