0

I am trying to login to a REST API with the following code:

NSError *serializationError = nil;

NSString* myString = @"{\"username\": \"xxx\",\"password\": \"xxx\",\"client_id\": \"Example\",\"grant_type\": \"password\",\"refresh_token\": \"string\"}";
NSData* myData = [myString dataUsingEncoding:NSUTF8StringEncoding];

NSData* params = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];


NSError *writeError = nil;

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&writeError];
NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"xxxxxxxxxxxxxxxxx"] cachePolicy:NSURLRequestReloadIgnoringCacheData  timeoutInterval:120];

[request setHTTPMethod:@"POST"];
[request setValue: @"application/json; encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setValue: @"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

[[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

    if (!error) {
        NSLog(@"Reply JSON: %@", responseObject);

        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            //blah blah
        }
    } else {

        NSLog(@"Error: %@", error);
        NSLog(@"Response: %@",response);
        NSLog(@"Response Object: %@",responseObject);

    }
}] resume];

But I am receiving an

Error: Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo={NSLocalizedDescription=Request failed: unacceptable content-type: text/html, NSErrorFailingURLKey=https:/xxxxxxxxxxxxx, com.alamofire.serialization.response.error.data=xxxxxxxxxxx, com.alamofire.serialization.response.error.response={ URL: https://xxxxxxxxxx } { Status Code: 200, Headers { "Content-Encoding" = ( gzip ); "Content-Type" = ( "text/html; charset=utf-8" ); Date = ( "Thu, 08 Mar 2018 10:34:31 GMT" ); Server = ( Kestrel ); "Transfer-Encoding" = ( Identity ); Vary = ( "Accept-Encoding" ); "X-Powered-By" = ( "ASP.NET" ); } }}

What is wrong?

Thanks.

mrd
  • 4,561
  • 10
  • 54
  • 92
  • https://stackoverflow.com/questions/19114623/request-failed-unacceptable-content-type-text-html-using-afnetworking-2-0 You need to add in accept content "text/html". – Larme Mar 08 '18 at 10:49
  • May this will get you in the right direction. [Check this url link.](https://stackoverflow.com/questions/34561215/afnetworking-3-0-migration-how-to-post-with-headers-and-http-body) – Mukesh Mar 08 '18 at 12:14

1 Answers1

0

This is not related to your issue, but seeing this, I had to tell you:

NSString* myString = @"{\"username\": \"xxx\",\"password\": \"xxx\",\"client_id\": \"Example\",\"grant_type\": \"password\",\"refresh_token\": \"string\"}";
NSData* myData = [myString dataUsingEncoding:NSUTF8StringEncoding];

NSData* params = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];


NSError *writeError = nil;

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&writeError];
NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

[request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];

Just don't do that.

What are the issue? Unnecessary code. What are you doing exactly?
JSONStringified (myString)
=> NSData (myData)
=> JSON Objective-C Equivalent Object NSDictionary (params, which by the way is a NSDictionary object, no a NSData object), dataWithObject:something will only accept something being a NSDictionary or a NSArray
=> NSData (jsonData)
=> JSONStringified (jsonString)
=> NSData (the HTTPBody).

What to do instead?

NSDictionary *params = @{@"username": @"xxx",
                         @"password": @"xxx",
                         @"client_id": @"Example",
                         @"grant_type": @"password",
                         @"refresh_token": @"string"};
NSData *jsonData = [NSJSONSerialization dataWithObject:params options: NSJSONWritingPrettyPrinted error:writeError];
[request setHTTPBody:jsonData];

Clearly, for sending JSON like this, I wouldn't use NSJSONWritingPrettyPrinted, seems useless (the server side shouldn't care) and have spaces/new lines which make the jsonData bigger (not necessary), so I'd write NSData *jsonData = [NSJSONSerialization dataWithObject:params options:0 error:writeError];

For the real issue of your question, you should add accept-content including text/html.

Larme
  • 24,190
  • 6
  • 51
  • 81
  • I replaced replaced [request setValue: @"application/json" forHTTPHeaderField:@"Accept"]; with [request setValue: @"text/html" forHTTPHeaderField:@"Accept"]; but I am getting still the same error. Any ideas? And according the API's Swagger definition it should be "application/json".... – mrd Mar 08 '18 at 12:05
  • Set the `manager.responseSerialiazer` to the `AFJSONResponseSerializer`, and set its `acceptableContentTypes` to text/html and application/json – Larme Mar 08 '18 at 12:12
  • My fault - turns out the problem was a typo in the url, but the mistyped url exists, so i was getting back html. But thanks for your kind help. – mrd Mar 08 '18 at 12:18