2012-09-16 12 views
14

Recibo esta respuesta en error.userInfo mientras realizo una solicitud POST desde AFNetworking. ¿Alguien puede decir que me falta algo obvio o que algo necesita arreglarse al final de mi servidor?AFNetworking y POST Request

Request Failed with Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {( "text/json", "application/json", "text/javascript")}, got text/html" UserInfo=0x6d7a730 {NSLocalizedRecoverySuggestion=index test, AFNetworkingOperationFailingURLResponseErrorKey=, NSErrorFailingURLKey=http://54.245.14.201/, NSLocalizedDescription=Expected content type {( "text/json", "application/json", "text/javascript")}, got text/html, AFNetworkingOperationFailingURLRequestErrorKey=http://54.245.14.201/>}, { AFNetworkingOperationFailingURLRequestErrorKey = "http://54.245.14.201/>"; AFNetworkingOperationFailingURLResponseErrorKey = ""; NSErrorFailingURLKey = "http://54.245.14.201/"; NSLocalizedDescription = "Expected content type {(\n \"text/json\",\n \"application/json\",\n
\"text/javascript\"\n)}, got text/html"; NSLocalizedRecoverySuggestion = "index test"; }

Y estoy usando este código;

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; 
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]]; 
[httpClient setDefaultHeader:@"Accept" value:@"application/json"]; 
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: 
         @"Ans", @"name", 
         @"29", @"age", 
         nil]; 

NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"/" parameters:params]; 

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request 
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
     NSLog(@"Success"); 
     NSLog(@"%@",JSON); 

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
     NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo); 
     NSLog(@"Failure"); 
}]; 

[operation start]; 
[operation waitUntilFinished]; 
+0

pregunta, ¿por qué tiene "[operation waitUntilFinished];"? ¿Es esto necesario y es una llamada de bloqueo? ¡Gracias! :) – trillions

+1

entonces ... ¿dónde/cómo en el código anterior implementó la solución aceptada? – Morkrom

Respuesta

46

Por defecto, AFJSONRequestOperation sólo acepta "text/json" , tipos de contenido "application/json" o "text/javascript" del servidor, pero obtendrá "text/html".

de fijación en el servidor sería mejor, pero también se puede añadir "text/html" tipo de contenido como aceptable en su aplicación:

[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]]; 

Funcionó para mí, espero que esto ayude!

4

¿Envió esta petición POST por AFHTTPClient? Si es así, es necesario establecer la clase de operación para que:

AFHTTPClient * client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://localhost:8080"]]; 
// ... 
[client registerHTTPOperationClass:[AFJSONRequestOperation class]]; 
[client setDefaultHeader:@"Accept" value:@"application/json"]; 
// ... 

// EDIT: Use AFHTTPClient's POST method 
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: 
         @"Ans", @"name", 
         @"29", @"age", nil]; 

// POST, and for GET request, you need to use |-getPath:parameters:success:failure:| 
[client postPath:@"/" 
     parameters:params 
     success:^(AFHTTPRequestOperation *operation, id responseObject) { 
      NSLog(@"RESPONSE: %@", responseObject); 
      // ... 
     } 
     failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
      if (error) 
      NSLog(@"%@", [error localizedDescription]); 
      // ... 
     } 
+0

Sí; Estoy usando AFHTTPClient, y también he establecido la clase mencionada; Por favor revisa mi código, solo edité mi pregunta; – Ans

+0

@Ans hay un método '-postPath: parameters: success:' para AFHTTPClient. ¿Lo has probado? – Kjuly

+0

Gracias por su respuesta; Probé tu código pero ahora ni el éxito ni el bloque de falla fueron ejecutados; – Ans

0

establecer los valores en este código y comprobar si funciona para usted

AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:kBASEURL]]; 
     NSString *_path = [NSString stringWithFormat:@"groups/"]; 
     _path = [_path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
     NSLog(@"%s %@",__PRETTY_FUNCTION__,_path); 
     NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" 
                   path:_path 
                  parameters:postParams]; 
     [httpClient release]; 

     AFJSONRequestOperation *operation = [AFJSONRequestOperation 
              JSONRequestOperationWithRequest:request 
              success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
               if ([JSON isKindOfClass:[NSArray class]] || [JSON isKindOfClass:[NSDictionary class]]) { 
                completed(JSON); 
               } 
               else { 
               } 
               [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];            

              } 
              failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
               NSLog(@" response %@ \n error %@ \n JSON %@",response,error,JSON); 
               [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];           
               errored(error); 
              }]; 

     NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease]; 
     [queue addOperation:operation]; 
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; 
+0

aquí kBASEURL le gustaría http://xyz.com/api y groups/es una API punto final, ¿verdad? ... bueno, lo intenté, pero cuando envió la llamada, no pasó nada; no estoy seguro de lo que realmente está sucediendo; incluso si mi URL no está en forma correcta, altest arrojar un error, etc. – Ans

+0

verifique la URL completa – yunas

+0

Pongo mi url base en lugar de kBASEURL y le pido que reemplace sus grupos/con mi punto final api; ¿eso está bien? – Ans