Keywords: AFNetworking | iOS | content-type | error handling | response serialization
Abstract: This article discusses the common error 'Request failed: unacceptable content-type: text/html' in AFNetworking 2.0, analyzing its causes and providing solutions such as modifying acceptableContentTypes or using different response serializers. Best practices for server-side fixes are also covered.
Problem Description
When using AFNetworking 2.0, developers may encounter the error "Request failed: unacceptable content-type: text/html". This occurs when the server returns a response with a Content-Type header that does not match the acceptable content types defined in the response serializer.
Error Analysis
AFNetworking 2.0 introduces a response serialization system where serializers like AFJSONResponseSerializer have a set of acceptable content types. By default, AFJSONResponseSerializer accepts "application/json", "text/json", etc., but not "text/html". If the server incorrectly sends HTML instead of JSON, the serializer rejects it, causing the error.
Solution: Modifying Acceptable Content Types
The primary solution, as suggested in the best answer, is to add "text/html" to the acceptableContentTypes set of the response serializer. This can be done by modifying the serializer instance.
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
op.responseSerializer.acceptableContentTypes = [op.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
This code snippet adds "text/html" to the existing set, allowing the serializer to accept HTML responses temporarily.
Alternative Solutions
Another approach is to use AFHTTPResponseSerializer instead, which does not enforce content type restrictions, as shown in Answer 2. However, this means you need to manually parse the response data.
op.responseSerializer = [AFHTTPResponseSerializer serializer];
Additionally, as in Answer 3, you can programmatically add "text/html" to the acceptable content types for all requests by modifying the manager's response serializer.
Best Practices
While client-side fixes are useful, the ideal solution is to correct the server to send the correct Content-Type, such as "application/json". This ensures compatibility and adheres to HTTP standards.
Conclusion
To handle unacceptable content-type errors in AFNetworking 2.0, developers can modify the acceptableContentTypes set or switch to a more permissive serializer. However, coordinating with server teams to fix the root cause is recommended for long-term stability.