我创建了一个生成的子类的子类,并尝试向服务器发送一些JSON参数。

但是,服务器正在响应预期内容类型

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

根据 afnetworking faq

如果您正在使用afhttpclient,请将parameterencoding属性设置为afjsonParameterEncoding。具有参数参数的HTTP客户端的任何方法现在将传递对象编码为JSON字符串,并适当地设置HTTP Body和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");
}
.

有帮助吗?

解决方案

问题是使用URL格式化。我没有注意到一个API实现详细信息,使得发送查询参数所必需的并且还在URI中指定JSON输出。

关于afnetworking没有问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top