Estoy probando la nueva versión 2.0 de AFNetworking y obtengo el error anterior. ¿Alguna idea de por qué sucede esto? Aquí está mi código:
NSURL *URL = [NSURL URLWithString:kJSONlink];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
Estoy usando Xcode 5.0.
Además, aquí está el mensaje de error:
Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0xda2e670 {NSErrorFailingURLKey=kJSONlink, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xda35180> { URL: kJSONlink } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Encoding" = gzip;
"Content-Length" = 2898;
"Content-Type" = "text/html";
Date = "Tue, 01 Oct 2013 10:59:45 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = Apache;
Vary = "Accept-Encoding";
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
Acabo de ocultar el JSON usando kJSONlink. Esto debería devolver un JSON.
ios
afnetworking
afnetworking-2
jaytrixz
fuente
fuente

op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];acceptableContentTypes:)op.responseSerializer.acceptableContentTypes = [op.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];op.responseSerializer.acceptableContentTypes = NSSet(object: "text/html")Configurar mi
RequestOperationManagerserializador de respuestas paraHTTPResponseSerializersolucionar el problema.C objetivo
Rápido
Hacer este cambio significa que no necesito agregar
acceptableContentTypesa cada solicitud que haga.fuente
AFJSONResponseSerializerresponseSerializerenAFJSONResponseSerializer.Llevé la respuesta / comentario de @jaytrixz un paso más allá y agregué "text / html" al conjunto de tipos existente. De esa forma, cuando lo arreglen en el lado del servidor a "application / json" o "text / json", afirmo que funcionará a la perfección.
fuente
En el lado del servidor, agregué:
en mi código .php y esto también solucionó el problema.
fuente
if(!headers_sent() ) { header('Content-Type: application/json'); }Es una buena soluciónResuelvo este problema desde una perspectiva diferente.
Creo que si el servidor envía datos JSON con
Content-Type: text/htmlencabezado. No significa que el chico del servidor pretendía enviarte un html pero cambió accidentalmente a JSON. Significa que al servidor no le importa cuál es elContent-Typeencabezado. Entonces, si al chico del servidor no le importa el lado del cliente, será mejor que ignore elContent-Typeencabezado también. Para ignorar elContent-Typeencabezado, regístreseAFNetworkingDe esta forma, el
AFJSONResponseSerializer(el predeterminado) serializará los datos JSON sin verificar elContent-Typeencabezado de respuesta.fuente
Una forma sencilla de permitir recibir el tipo de contenido "text / plain":
Del mismo modo, si desea habilitar el tipo de contenido "text / html":
fuente
Intenté debajo de la línea según la respuesta de @Andrie pero no funcionó,
así que después de buscar más, trabajé para que funcionara con éxito.
Aquí está mi fragmento de código.
Espero que esto ayude a alguien por ahí.
fuente
Esto es lo único que encontré que funciona
fuente
Si alguien está usando
AFHTTPSessionManager, uno puede hacer esto para resolver el problema,Subclase
AFHTTPSessionManagerdonde estoy haciendo esto,fuente
En mi caso, no tengo control sobre la configuración del servidor, pero sé que espera "application / json" para "Content-Type". Hice esto en el lado del cliente iOS:
consulte el error de tipo de contenido de AFNetworking versión 2
fuente
Solo agrega esta línea:
fuente
Tuve un problema similar al trabajar con AFNetworking desde una base de código Swift, así que lo dejo aquí en el caso remoto de que alguien tenga tanta mala suerte como yo tener que trabajar en una configuración de este tipo. Si es así, te siento amigo, ¡mantente fuerte!
La operación estaba fallando debido al "tipo de contenido inaceptable", a pesar de que en realidad configuré
acceptableContentTypescon unSetvalor de tipo de contenido en cuestión.La solución para mí fue ajustar el código Swift para que sea más amigable con Objective-C, supongo :
fuente
Una buena pregunta siempre tiene múltiples respuestas, para reducir y ayudarlo a elegir la respuesta correcta, aquí también estoy agregando la mía. Lo he probado y funciona bien.
fuente
fuente