1

我创建了一个子类,AFHTTPClient并试图将一些 JSON 参数发送到服务器。

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

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

根据AFNetworking 常见问题解答

如果您使用的是 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");
}
4

1 回答 1

1

问题在于 URL 格式。我没有注意到需要发送查询参数并在 URI 中指定 JSON 输出的 API 实现细节。

AFNetworking 没有任何问题。

于 2012-07-27T20:40:42.557 回答