Programming

Request failed unacceptable content-type texthtml using AFNetworking 20

27 September 2026 · 9 min read

Request failed unacceptable content-type texthtml using AFNetworking 20

Encountering the “Request failed: unacceptable content-type: text/html” error when using AFNetworking 2.0 can be a frustrating roadblock in your iOS or macOS development journey. This error typically arises when your application expects a specific content type (like JSON or XML) from a server, but instead receives an HTML response. This discrepancy indicates a mismatch between what your app requests and what the server delivers. Understanding the root cause and implementing the correct solutions are crucial for ensuring seamless data communication between your app and the server. This article will guide you through diagnosing and resolving this common AFNetworking 2.0 issue, providing practical examples and best practices to ensure your network requests are successful.

Understanding the “Unacceptable Content-Type” Error

The “Request failed: unacceptable content-type: text/html” error within AFNetworking 2.0 signifies a content type mismatch. Your AFNetworking client is configured to expect a particular data format (usually JSON, XML, or a custom format), but the server responds with HTML. This commonly happens when the server encounters an error, such as a 404 Not Found or a 500 Internal Server Error, and returns an HTML error page instead of the expected data. This error is not an issue within AFNetworking itself, but rather a symptom of a problem on the server-side or a misconfiguration in your request parameters. Properly handling this error is essential for a robust and user-friendly application. Ignoring it can lead to unexpected app behavior and a poor user experience.

To effectively diagnose this issue, it’s important to examine the server’s response. Use tools like Charles Proxy [External link: Charles Proxy] or Paw [External link: Paw] to inspect the HTTP headers and body of the server’s response. The “Content-Type” header in the response will reveal the actual format being returned. If it’s “text/html,” then the server is indeed sending an HTML document, even if your app expects JSON or XML. Furthermore, the response body will likely contain the HTML error page, providing clues as to why the server failed to return the expected data. Confirm your request is correctly formed and that the server endpoint you are targeting is valid.

Consider a scenario where your app is designed to fetch user profiles from a server in JSON format. If the user ID in your request is invalid, the server might return an HTML error page indicating “User not found.” Your AFNetworking client, expecting JSON, would then throw the “Request failed: unacceptable content-type: text/html” error. This example highlights the importance of validating your request parameters and handling potential server-side errors gracefully.

Common Causes and Diagnostic Steps

Several factors can contribute to the “Request failed: unacceptable content-type: text/html” error when using AFNetworking 2.0. Identifying the root cause is crucial for implementing the correct solution. Here’s a breakdown of common causes and steps to diagnose them:

  • Incorrect API Endpoint: Double-check that the URL you’re using in your AFNetworking request is correct and points to the intended API endpoint. A typo or an outdated URL can easily lead to the server returning an HTML error page.
  • Server-Side Errors: The server might be experiencing internal errors (500 status code), resource not found errors (404 status code), or other issues that cause it to return an HTML error page instead of the expected JSON or XML.
  • Content Negotiation Issues: Your request might not be explicitly specifying the desired content type (e.g., “Accept: application/json” in the HTTP header). The server might then default to returning HTML.
  • Authentication Problems: If your API requires authentication, ensure that your request includes the necessary authentication credentials (e.g., API key, OAuth token). Lack of proper authentication can result in the server returning an HTML login page or an error message.

To diagnose the issue, start by inspecting the server’s response using a network debugging tool like Charles Proxy. Examine the HTTP status code, headers, and body. A 4xx or 5xx status code indicates a server-side problem. The “Content-Type” header will confirm whether the server is indeed returning HTML. The response body will contain the HTML error page, providing clues about the nature of the error. Next, verify that your request URL, parameters, and authentication credentials are correct. Compare your request to the API documentation to ensure that you’re sending the correct information in the expected format.

A real-world scenario might involve an e-commerce app that fetches product details from a server. If the server’s database is temporarily unavailable, it might return a 500 Internal Server Error with an HTML error page. The app, expecting JSON product data, would then encounter the “Request failed: unacceptable content-type: text/html” error. Implementing proper error handling and retry mechanisms can help mitigate such issues.

Solutions and Code Examples

Once you’ve identified the cause of the “Request failed: unacceptable content-type: text/html” error, you can implement the appropriate solution. Here are several approaches, along with code examples using AFNetworking 2.0:

1. Explicitly Set the Accept Header: Ensure your request includes the “Accept” header specifying the desired content type. This tells the server what format your client expects. This is a good practice, even if the server should default to the format you expect.

AFHTTPRequestOperationManager manager = [AFHTTPRequestOperationManager manager]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"]; [manager GET:@"https://api.example.com/data" parameters:nil success:^(AFHTTPRequestOperation operation, id responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(AFHTTPRequestOperation operation, NSError error) { NSLog(@"Error: %@", error); }]; 

Featured Snippet Optimization: The most common solution is to explicitly set the acceptable content types for your AFHTTPRequestOperationManager. By specifying that you only accept application/json, you are telling AFNetworking to reject responses that do not match this type. This prevents the error from occurring when the server returns HTML. Make sure your server is indeed configured to send JSON responses for the endpoint you are querying.

2. Handle Server Errors Gracefully: Implement error handling to gracefully manage server-side errors. Check the HTTP status code in the failure block and provide informative error messages to the user. Consider using AFNetworking’s built-in error handling mechanisms.

AFHTTPRequestOperationManager manager = [AFHTTPRequestOperationManager manager]; [manager GET:@"https://api.example.com/data" parameters:nil success:^(AFHTTPRequestOperation operation, id responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(AFHTTPRequestOperation operation, NSError error) { NSLog(@"Error: %@", error); if (operation.response.statusCode == 404) { NSLog(@"Resource not found."); // Handle 404 error } else if (operation.response.statusCode == 500) { NSLog(@"Internal server error."); // Handle 500 error } else { NSLog(@"Other error: %@", error); // Handle other errors } }]; 

3. Verify API Endpoint and Parameters: Double-check the URL and parameters you’re using in your request. Ensure they are correct and match the API documentation. Use a tool like Postman [External link: Postman] to test the API endpoint independently.

For example, consider a mobile app for booking flights. If the app sends an invalid date format to the server when searching for flights, the server might return an HTML error page. By validating the date format on the client-side and ensuring it matches the server’s expected format, you can prevent the “Request failed: unacceptable content-type: text/html” error.

Best Practices and Troubleshooting

To prevent and troubleshoot the “Request failed: unacceptable content-type: text/html” error in AFNetworking 2.0, consider these best practices:

  1. Always Specify Acceptable Content Types: Explicitly set the acceptableContentTypes property of your AFHTTPRequestOperationManager to the content types your app expects.
  2. Implement Robust Error Handling: Handle server-side errors gracefully, providing informative error messages to the user and logging errors for debugging.
  3. Validate Input Data: Validate user input and request parameters to prevent invalid data from being sent to the server.
  4. Use Network Debugging Tools: Use tools like Charles Proxy or Paw to inspect network traffic and diagnose issues.
  5. Monitor Server Logs: Monitor server logs to identify and resolve server-side errors.

Here are some additional troubleshooting tips:

  • Check for Redirections: Ensure that your request is not being redirected to an HTML page. AFNetworking might not handle redirections correctly in some cases.
  • Verify Server Configuration: Verify that the server is configured to send the correct content types for the requested endpoints.
  • Test with Different Devices and Networks: Test your app on different devices and networks to rule out device-specific or network-related issues.

For instance, a social media app might encounter this error if the server is temporarily overloaded and returns an HTML “Service Unavailable” page. Implementing retry mechanisms with exponential backoff can help the app recover gracefully from such temporary server issues. Furthermore, ensure your error messages are user-friendly, guiding them on how to resolve the problem, such as checking their internet connection or trying again later. This demonstrates a commitment to a positive user experience, even in the face of technical challenges.

FAQ

**Q: Why am I getting "Request failed: unacceptable content-type: text/html" even when the server should be sending JSON?**
A: Double-check the server-side code to ensure it's actually sending the correct Content-Type header ("application/json"). Also, verify that there are no server-side errors (like 404 or 500) causing it to return an HTML error page instead.
**Q: How do I set the Accept header in AFNetworking 2.0?**
A: You don't directly set the "Accept" header. Instead, you modify the acceptableContentTypes property of the responseSerializer of your AFHTTPRequestOperationManager. This tells AFNetworking which content types to accept.
**Q: Is this error always a server-side problem?**
A: Not always. While it often indicates a server-side issue, it can also be caused by incorrect API endpoints, missing authentication credentials, or misconfigured AFNetworking settings on the client-side.
By understanding the nature of the "**Request failed: unacceptable content-type: text/html**" error and implementing the solutions and best practices outlined in this article, you can ensure your AFNetworking 2.0-based applications are robust and reliable. Remember to always validate your request parameters, handle server errors gracefully, and use network debugging tools to diagnose issues effectively. This proactive approach will save you time and effort in the long run, leading to a smoother development experience and a better user experience for your app.

Don’t let networking errors derail your app’s success. Take these strategies and apply them to your current projects. Are you struggling with other AFNetworking issues? Explore our related articles on request serialization and response parsing for more in-depth guidance. By continuing to learn and refine your skills, you’ll build more resilient and user-friendly applications.

Question & Answer :
I’m trying out the new version 2.0 of AFNetworking and I’m getting the error above. Any idea why this is happening? Here’s my code:

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]; 

I’m using Xcode 5.0.

Also, here’s the error message:

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} 

I just hid the JSON using kJSONlink. This should return a JSON.

This means that your server is sending "text/html" instead of the already supported types. My solution was to add "text/html" to acceptableContentTypes set in AFURLResponseSerialization class. Just search for “acceptableContentTypes” and add @"text/html" to the set manually.

Of course, the ideal solution is to change the type sent from the server, but for that you will have to talk with the server team.