Pergunta

Eu criei uma subclasse de AFHTTPClient e estou tentando enviar alguns parâmetros JSON para um servidor.

No entanto, o servidor está respondendo com um tipo de conteúdo esperado

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

De acordo com Perguntas frequentes sobre AFNetworking

Se você estiver usando AFHTTPClient, defina a propriedade parâmetroEncoding como AFJSONParameterEncoding.Qualquer método nesse cliente HTTP com um argumento de parâmetros agora codificará o objeto passado em uma string JSON e definirá o corpo HTTP e o cabeçalho Content-Type adequadamente.

Eu fiz isso aqui, mas o servidor parece não reconhecer os cabeçalhos de conteúdo.Alguém sabe de uma solução potencial?

Aqui está o método:

- (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");
}
Foi útil?

Solução

O problema estava na formatação do URL.Não notei um detalhe de implementação da API que tornasse necessário o envio de parâmetros de consulta e também a especificação da saída JSON no URI.

Não houve problemas em relação à AFNetworking.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top