Request failed: unacceptable content-type: text/html using AFNetworking 2.0
Asked Answered
S

14

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.

Skedaddle answered 1/10, 2013 at 11:9 Comment(0)
M
365

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.

Mediative answered 1/10, 2013 at 16:21 Comment(10)
Thanks! I just added this code to make it work: op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];Skedaddle
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)Confiscable
@Confiscable Thanks for this - much preferred to change the page header than acceptableContentTypes :)Ugrian
An alternative to @Skedaddle comment is to just add a new content type to the already existing ones: op.responseSerializer.acceptableContentTypes = [op.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];Monsoon
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.Explication
Swift code: op.responseSerializer.acceptableContentTypes = NSSet(object: "text/html")Hightension
Thanks dude! self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];Dialogize
Adding one more content type to the existing set is the possible way AFHTTPSessionManager_insatnce.responseSerializer.acceptableContentTypes = [AFHTTPSessionManager_insatnce.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];Scutum
If that happens in Parse.com platform that because you used the wrong keys such as restAPI key and not client key, etcBenzocaine
Swift 2.2 is like the following NSSet(object: "text/html") as? Set<String>Viewless
A
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.

Alisa answered 5/10, 2013 at 18:33 Comment(8)
I made this and it crashes my app. Reverting back to using AFJSONResponseSerializerSkedaddle
@Skedaddle It depends, If your server always responds with JSON you should set the responseSerializer to AFJSONResponseSerializer.Alisa
You will now receive the responseObject as NSData and need to parse the JSON in the success block.Del
Because I am using pods, so this way is better.Countertenor
@Danpe, How to convert above line of code into Swift. I tried with manager.responseSerializer = AFJSONResponseSerializer.serializer() but no use.Coquillage
Hey @G.Ganesh I updated my answer, try manager.responseSerializer = AFHTTPResponseSerializer.serializer()Alisa
The Swift version should be manager.responseSerializer = AFHTTPResponseSerializer()Surrogate
@ Danpe, You are my Hero for the Day........ Thanks Buddy, works like a charm.....Kilogrammeter
S
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"];
Sulphurous answered 15/2, 2014 at 22:54 Comment(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.Chyack
This seems right in theory but has anyone actually tested this?Thill
K
33

On the server side, I added:

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

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

Kirmess answered 10/10, 2013 at 19:1 Comment(1)
if(!headers_sent() ) { header('Content-Type: application/json'); } Is a nice fixNatalee
N
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.

Nassi answered 27/1, 2015 at 3:44 Comment(1)
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 youIllinois
C
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"];
Chokeberry answered 3/6, 2014 at 18:20 Comment(0)
L
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.

Landpoor answered 9/7, 2015 at 11:58 Comment(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.Janusfaced
B
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);
    }];
}
Botnick answered 22/8, 2014 at 19:36 Comment(0)
H
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;
Hellbent answered 30/9, 2014 at 11:42 Comment(0)
L
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

Leola answered 2/9, 2014 at 1:26 Comment(0)
P
1

Just add this line :

operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
Phonation answered 19/6, 2015 at 8:8 Comment(0)
H
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);
}];
Hellbent answered 13/7, 2016 at 6:2 Comment(0)
T
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>
Torritorricelli answered 16/5, 2016 at 1:56 Comment(0)
C
-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);
 }];
Cavern answered 18/8, 2014 at 6:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.