208

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
jaytrixz
  • 4,059
  • 7
  • 38
  • 57

14 Answers14

364

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.

Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
Andrei Neag
  • 3,749
  • 1
  • 12
  • 7
  • 142
    Thanks! I just added this code to make it work: `op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];` – jaytrixz Oct 02 '13 at 02:08
  • 13
    For PHP it's as easy as adding this to the page: header("Content-Type: application/json"); (unless it's not a JSON response, then XML or something) – rckehoe Dec 06 '13 at 15:02
  • 1
    @rckehoe Thanks for this - much preferred to change the page header than `acceptableContentTypes` :) – Nick May 01 '14 at 08:49
  • 43
    An alternative to @jaytrixz comment is to just _add_ a new content type to the already existing ones: `op.responseSerializer.acceptableContentTypes = [op.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];` – mgarciaisaia Jul 03 '14 at 17:12
  • If you are dealing with standard API you will never have to do that, adding text/html as a type and sending JSON is bad practice. Changing server code is proper solution. – vishal dharankar Jul 04 '14 at 08:50
  • 11
    Swift code: `op.responseSerializer.acceptableContentTypes = NSSet(object: "text/html")` – Husam Dec 21 '14 at 09:58
  • Thanks dude! self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil]; – prakash singh Feb 02 '15 at 09:25
  • Adding one more content type to the existing set is the possible way AFHTTPSessionManager_insatnce.responseSerializer.acceptableContentTypes = [AFHTTPSessionManager_insatnce.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"]; – Rahul K Rajan Oct 26 '15 at 05:59
  • If that happens in Parse.com platform that because you used the wrong keys such as restAPI key and not client key, etc – dang Jan 03 '16 at 16:04
  • Swift 2.2 is like the following ```NSSet(object: "text/html") as? Set``` – Andrew Apr 29 '16 at 16:21
179

Setting my RequestOperationManager Response Serializer to HTTPResponseSerializer fixed the issue.

Objective-C

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

Swift

manager.responseSerializer = AFHTTPResponseSerializer()

Making this change means I don't need to add acceptableContentTypes to every request I make.

Danpe
  • 18,668
  • 21
  • 96
  • 131
73

I took @jaytrixz's answer/comment one step further and added "text/html" to the existing set of types. That way when they fix it on the server side to "application/json" or "text/json" I claim it'll work seamlessly.

  manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
mharper
  • 3,212
  • 1
  • 23
  • 23
  • 2
    Agreed. The accepted answer to this question has a huge flaw in that it creates a time bomb that will explode when the server side is fixed to return the correct content type. – Eric G Feb 25 '15 at 23:08
  • This seems right in theory but has anyone actually tested this? – Minimi Dec 01 '16 at 19:31
33

On the server side, I added:

header('Content-type: application/json');

into my .php code and this also fixed the problem.

Chris Prince
  • 7,288
  • 2
  • 48
  • 66
18

I solve this problem from a different perspective.

I think if the server sends JSON data with Content-Type: text/html header. It doesn't mean the server guy intended to send you some html but accidentally changed to JSON. It does mean the server guy just doesn't care about what the Content-Type header is. So if the server guy doesn't care as the client side you better ignore the Content-Type header as well. To ignore the Content-Type header check in AFNetworking

manager.responseSerializer.acceptableContentTypes = nil;

In this way the AFJSONResponseSerializer (the default one) will serialize the JSON data without checking Content-Type in response header.

dopcn
  • 4,218
  • 3
  • 23
  • 32
  • Exactly correct. By ignoring the content type I do not receive my content as a hex code, nor as a failed nil response. This works great! Thank you – Brandon Nov 17 '15 at 16:37
7

A simple way to enable to receive "text/plain" content type:

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

Similarly if you wish to enable "text/html" content type:

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
Aman Satija
  • 1,865
  • 2
  • 15
  • 16
da Rocha Pires
  • 2,443
  • 1
  • 24
  • 19
5

I tried below line as per @Andrie answer but didn't work,

op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

so after hunting more, I did work around to get it work successfully.

Here is my code snip.

AFHTTPRequestOperationManager *operation = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    AFJSONResponseSerializer *jsonResponseSerializer = [AFJSONResponseSerializer serializer];

    NSMutableSet *jsonAcceptableContentTypes = [NSMutableSet setWithSet:jsonResponseSerializer.acceptableContentTypes];
    [jsonAcceptableContentTypes addObject:@"text/plain"];
    jsonResponseSerializer.acceptableContentTypes = jsonAcceptableContentTypes;
    operation.responseSerializer = jsonResponseSerializer;

Hope this will help someone out there.

ABS
  • 7,634
  • 1
  • 21
  • 20
  • 1
    +1. This is definitively the solution. Since you have to set the acceptable Content Type both on the Serializer if this is a JSON serializer (that is normally using "application/json") and the operation. Otherwise you will get an error settings on operation only. – loretoparisi Sep 24 '15 at 14:22
3

This is the only thing that I found to work

-(void) testHTTPS {
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager setSecurityPolicy:securityPolicy];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [manager GET:[NSString stringWithFormat:@"%@", HOST] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}
chrisallick
  • 1,330
  • 17
  • 18
3

If someone is using AFHTTPSessionManager then one can do like this to solve the issue,

I subclassed AFHTTPSessionManager where I'm doing like this,

NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:self.responseSerializer.acceptableContentTypes];
[contentTypes addObject:@"text/html"];
self.responseSerializer.acceptableContentTypes = contentTypes;
Hemang
  • 26,840
  • 19
  • 119
  • 186
2

In my case, I don't have control over server setting, but I know it's expecting "application/json" for "Content-Type". I did this on the iOS client side:

manager.requestSerializer = [AFJSONRequestSerializer serializer];

refer to AFNetworking version 2 content-type error

Community
  • 1
  • 1
uudaddy
  • 341
  • 4
  • 9
1

Just add this line :

operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
elp
  • 8,021
  • 7
  • 61
  • 120
Elangovan
  • 1,158
  • 1
  • 9
  • 26
1

A good question always have multiple answers, to reduce and help you choose the right answer, here I am adding my own too. I have tested it and it works fine.

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.yourdomain.com/appname/data/ws/index.php/user/login/"]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

[manager POST:@"POST" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSString *json = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"%@", json);
    //Now convert json string to dictionary.
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"%@", error.localizedDescription);
}];
Hemang
  • 26,840
  • 19
  • 119
  • 186
0

I had a somehow similar problem working with AFNetworking from a Swift codebase so I'm just leaving this here in the remote case someone is as unlucky as me having to work in such a setup. If you are, I feel you buddy, stay strong!

The operation was failing due to "unacceptable content-type", despite me actually setting the acceptableContentTypes with a Set containing the content type value in question.

The solution for me was to tweak the Swift code to be more Objective-C friendly, I guess:

serializer.acceptableContentTypes = NSSet(array: ["application/xml", "text/xml", "text/plain"]) as Set<NSObject>
mokagio
  • 16,391
  • 3
  • 51
  • 58
-1
 UIImage *image = [UIImage imageNamed:@"decline_clicked.png"];
NSData *imageData = UIImageJPEGRepresentation(image,1);


NSString *queryStringss = [NSString stringWithFormat:@"http://119.9.77.121/lets_chat/index.php/webservices/uploadfile/"];
queryStringss = [queryStringss stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

[MBProgressHUD showHUDAddedTo:self.view animated:YES];


[manager POST:queryStringss parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
 {


     [formData appendPartWithFileData:imageData name:@"fileName" fileName:@"decline_clicked.png" mimeType:@"image/jpeg"];



 }
      success:^(AFHTTPRequestOperation *operation, id responseObject)
 {



    NSDictionary *dict = [responseObject objectForKey:@"Result"];

    NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];


 }
      failure:^(AFHTTPRequestOperation *operation, NSError *error)
 {
     [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
     NSLog(@"Error: %@ ***** %@", operation.responseString, error);
 }];
Waseem Sarwar
  • 2,645
  • 1
  • 21
  • 18