NSURLSession: Getting 401 HTTP error - objective-c

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.

Try to put a slash "/" at the end of the url.

Related

Https Post in objective c

I have the below code for http post request,
FIRDatabaseReference *agreementCreateReference = [[[FIRDatabase database] referenceWithPath:#"/agreements/"] childByAutoId];
NSLog(#"autoId %#",agreementCreateReference.key);
NSLog(#"autoId %#",_propertyId);
NSString *post = [NSString stringWithFormat:#"agreementId=%#&listingId=%#",agreementCreateReference.key,_propertyId];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://krib-api-onbit.herokuapp.com/api/agreements"]];
[request setHTTPMethod:#"POST"];
[request setValue:idToken forHTTPHeaderField:#"X-FIREBASE-ID-TOKEN"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"%#",request);
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"data dtat %#",data);
}];
[dataTask resume];
This url with parameters and headers returns data in the Postman. When I use to get data using objective c using the above code I get <42616420 52657175 6573740a> as data. And not calling the backend either.
After spending hours on this issue, I just sent the parameters via the URl and it returned data and printed the request in the backend. Code is as follows for anyone.
FIRDatabaseReference *agreementCreateReference = [[[FIRDatabase database] referenceWithPath:#"/agreements/"] childByAutoId];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *url = [NSString stringWithFormat:#"https://krib-api-onbit.herokuapp.com/api/agreements?agreementId=%#&listingId=%#",agreementCreateReference.key,_propertyId];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:idToken forHTTPHeaderField:#"X-FIREBASE-ID-TOKEN"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//[request setHTTPBody:postData];
NSLog(#"%#",request);
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"data dtat %#",data);
NSString *res = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"res %#",res);
}];
[dataTask resume];

What is JIRA rest api to logout an user and is the below the correct approach to login and logout an user using JIRA Rest api?

I am developing an iOS application that connects with jira instance and i login using NSURLConnection like below -
NSString *authStr =[[NSString alloc] initWithFormat:#"%#:%#",[self.txtUsername text],[self.txtPassword text]];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://hp.myDomain.com/rest/api/2/issue/createmeta?"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
and as i am using a BASIC authentication which is stateless and i wanted to know how can i logout the user now , i have tried the below code when a logout button is clicked . Can anyone please let me know if it is the right code and what is the right rest api for jira to logout an user?
-(IBAction)logout:(NSURLConnection *)conn
{
NSError *error;
NSURLResponse *response;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.myDoamin.co/logout.htm"]];
[request setHTTPMethod:#"GET"];
//[request setTimeoutInterval:30.0];
[conn initWithRequest:request delegate:self];
}

Objective C webservice request works with http:// but not https://

Any suggestions? The code works perfectly with http but not https://. I wonder if it's the port. The certificate is valid. I get a "server pretending to be another server" error.
NSString *post=[[NSString alloc] initWithFormat:#"strEmail=%#&strPassword=%#", [self.txtUsername text], [self.txtPassword text]];
NSLog(#"PostData%#", post);
// NSURL *url= [NSURL URLWithString:#"http://dipinkrishna.com/jsonlogin.php"]; // does work
NSURL *url= [NSURL URLWithString:#"https://dev.myrdcm.com/felipe.asmx?op=GetSignIn”];// does not work
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-fore-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"%#",request);
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse * response = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
If you get a "server pretending to be another server" error, then certificate is not valid. I have opened yours url in browser and see that certificate is expired.

Can't POST a request to service

For some reason I always get Endpoint not found., but when I put it in the browser it works perfectly. I'm sure doing something wrong..
- (void)requestLoad:(NSString *)req_udid Age:(NSString *)req_age Gender:(NSString *)req_gender CheckBoxes:(NSString *)req_checkBoxes
{
NSString *post = [NSString stringWithFormat:#"/UpdatePersonalInterests/%#/%#/%#/%#/0",req_udid, req_age, req_gender, req_checkBoxes];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//set up the request to the website
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:NSLocalizedStringFromTable(#"kServiceURL", #"urls", nil)]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",result);
}
Thanks!
It looks like you are using a Custom Service scheme. Did you register it in Target -> info - URLS Types? See the Apple Docs or Registering custom URL Schemes: Implementing Custom URL Schemes
So I've managed to do this with NSURLConnection and asynchronous request with this code:
- (void)getIntrests
{
NSString *req_udid = [PROUtils createOrLoadUserIdentifier];
NSString *webaddress = [kServiceBaseURL stringByAppendingString:[NSString stringWithFormat:#"/GetPersonalInterestsForUdid/%#",req_udid]];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:webaddress] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:
^(NSURLResponse* response, NSData* data, NSError* error) {
NSString* dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:kGotMediaFromServer object:dataString];
NSLog(#"Update response completed: %# with data: %# error: %#",response,dataString,error);
}];
}
Hope that it will be useful for someone.

Objective-C Asynchronous NSURLConnection to Ruby Server

I am having trouble sending asynchronous NSURLRequests to a Ruby server. When I use the following, a connection is never made:
self.data = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://domain.com/app/create_account.json"]];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request addValue:#"form-data" forHTTPHeaderField:#"Content-Disposition"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
However, when I exchange the last line with:
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
Everything works great. But I do need to make this connection asynchronously...
EDIT-Working Example
NSURL *url = [NSURL URLWithString:#"http://domain.com/app/create_account.json"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:data forKey:#"data"];
[request setDelegate:self];
[request startAsynchronous];
It seems RESTful services need their own third party framework in this case.
you can try following using restkit api
- (void)sendAsJSON:(NSDictionary*)dictionary {
RKClient *client = [RKClient clientWithBaseURL:#"http://restkit.org"];
// create a JSON string from your NSDictionary
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
NSError *error = nil;
NSString *json = [parser stringFromObject:dictionary error:&error];
// send your data
if (!error)
[[RKClient sharedClient] post:#"/some/path" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self];
}
referance:
https://github.com/RestKit/RestKit/wiki/Tutorial-%3A-Introduction-to-RestKit
https://github.com/RestKit/RestKit/wiki/Posting-NSDictionary-as-JSON
Thanks
Nikhil