I am getting "401 Unauthorized access to the endpoint". When I run the same call on POSTMAN (Chrome Extension), it works fine. Even it works fine in my Android app.
But here, I am getting the unauthorized access even if I am sending token in headers. I have no idea what is going wrong here. The response I am getting is:
{"detail":"Authentication credentials were not provided."}
Here is my code:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *url=[NSString stringWithFormat:@"%@",endpoint];
NSLog(@"url is %@",url);
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSString *token=[NSString stringWithFormat:@"token %@",TOKEN];
NSLog(@"token is %@",token);
[request addValue:token forHTTPHeaderField:@"Authorization"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"requestReply: %@", requestReply);
}] resume];
What and where am I doing something wrong?
Edit: If I tried this way by using different class, the response is (null).
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL
URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10
];
[request setHTTPMethod: @"GET"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSString *token=[NSString stringWithFormat:@"token %@",[[NSUserDefaults standardUserDefaults]valueForKey:D_KEY_TOKEN]];
[request setValue:token forHTTPHeaderField:@"Authorization"];
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
[NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse error:&requestError];
NSLog(@"url response is %@",urlResponse);
Edit2:
NSString *url=[NSString stringWithFormat:@"%@/",endpoint];
This is what I have done just append the slash(/)at the end of endpoint at it starts working. I want to know why there is a need to append slash at the end? All my other calls are working without slash.