AFNetworking http客户端不发送JSON参数

时间:2012-07-27 19:42:07

标签: ios ios5 nsurlrequest afnetworking

我创建了AFHTTPClient的子类,并尝试将一些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 个答案:

答案 0 :(得分:1)

问题在于网址格式化。我没有注意到一个API实现细节,它使得必须发送Query Parameters并在URI中指定JSON输出。

AFNetworking没有问题。