2012-07-27 48 views
1

我创建了AFHTTPClient的子类,并试图发送一些JSON参数给服务器。AFNetworking http客户端不发送JSON参数

但是服务器响应与预期的内容类型

{(
    "text/json", 
    "application/json", 
    "text/javascript" 
)}, got application/xml 

根据AFNetworking FAQ

如果您使用AFHTTPClient,该parameterEncoding属性设置为AFJSONParameterEncoding。该HTTP客户端上带有参数参数的任何方法现在都会将传递的对象编码为JSON字符串,并适当地设置HTTP正文和Content-Type标头。

我已经这样做了,但服务器似乎无法识别内容头。有谁知道一个潜在的解决方案?

这里是方法:

- (void)getCompanyDataWithString:(NSString*)companySearchQuery 
     finish:(LBMarkitAPIRequestCompletionBlock)finishBlock 
{ 
    [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; 
    [self setParameterEncoding:AFJSONParameterEncoding]; 

    NSDictionary *params = [NSDictionary dictionaryWithObject: 
     companySearchQuery forKey:@"input"]; 
    NSMutableURLRequest *searchQueryRequest = [self requestWithMethod:@"GET" 
     path:kMarkitCompanyURL parameters:params]; 

    AFJSONRequestOperation *searchRequestOperation = [AFJSONRequestOperation 
     JSONRequestOperationWithRequest:searchQueryRequest 
     success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) 
     { 
      NSLog(@"Response: %@", response); 
      NSLog(@"JSON: %@",json); 
      NSMutableArray *results = [NSMutableArray array]; 

      NSError *anError = [[NSError alloc] init]; 
      if ([json objectForKey:@"Message"]) 
      { 
       NSString *message = [json objectForKey:@"Message"]; 
       anError = [[NSError alloc] initWithDomain:message 
                code:100 
               userInfo:nil]; 
      } 

      // Need some error handling code here 
      for (id item in json) 
      { 
       NSString *aName = [item objectForKey:@"Name"]; 
       NSString *aSymbol = [item objectForKey:@"Symbol"]; 
       NSString *anExchange = [item objectForKey:@"Exchange"]; 

       LBCompany *aCompany = [[LBCompany alloc] initWithName:aName 
        Symbol:aSymbol Exchange:anExchange]; 
       [results addObject:aCompany]; 
      } 
      // Need to run the passed in block after JSON 
      // Request Operation succeeds 

      finishBlock(results,anError); 
      } 
     failure:^(NSURLRequest *request, NSHTTPURLResponse *response, 
      NSError *error, id JSON) 
     { 
      NSLog(@"request failed: %@",[error localizedDescription]); 
      NSLog(@"Response: %@",response); 
      NSLog(@"JSON: %@",JSON); 
     }]; 

    [searchRequestOperation start]; 
    NSLog(@"JSON operation started"); 
} 

回答

1

的问题是与URL格式。我没有注意到一个API实现细节,它使发送查询参数成为必需,并且还指定了URI中的JSON输出。

AFNetworking没有问题。

+0

嗨,我想我有同样的问题,但还没有想出如何解决它。你能告诉我更多关于你在做什么错误的API和你如何修复它。 – filo 2013-06-21 08:49:51

+0

你可以在这里查看我的解决方案:http://github.com/andrewjl/Aperio/blob/master/Aperio/LBHTTPClient.m – 2013-06-27 19:12:37

+0

谢谢,它帮助了我。 – filo 2013-06-28 17:40:01

相关问题