I need to show Garmin health data in my app. Garmin documentation ask developer to implement connection thorough oauth 1.0 connection with the app and garmin account. So, when i apply GET/PUSH request with the https://connectapi.garmin.com/oauth-service/oauth/request_token? url, its shows the following error. Fortunately , i am getting proper response in the postman.
Step 1 :
Postman request :
https://connectapi.garmin.com/oauth-service/oauth/request_token?oauth_consumer_key=3f58949f-e54d-4211-a735-e52cc0ab8f4d&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1531983278&oauth_nonce=cW1Xhs&oauth_version=1.0&oauth_signature=WveKS0cnl7w4ZNknL0WD4f7wBFU=
Response :
oauth_token=48d03142-ffe3-4adc-ae0e-6c3d7bdd1e18&oauth_token_secret=EY67QDeBqHNvCzlCt0HU5yQ1LkVkGOMK0b4
In my Code , I apply both GET/POST request, it shows following error :
Garmin Connect API Server - Error report HTTP Status 400 - Inadequate OAuth consumer credentials.type Status reportmessage Inadequate OAuth consumer credentials.description The request sent by the client was syntactically incorrect.Garmin Connect API Server
My code is like :
NSError *error;
NSString *urlString = #"https://connectapi.garmin.com/oauth-service/oauth/request_token?";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString * parameterString = [NSString stringWithFormat:#"oauth_consumer_key=3f58949f-e54d-4211-a735-e52cc0ab8f4d&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1531983278&oauth_nonce=cW1Xhs&oauth_version=1.0&oauth_signature=pfZzKhniC9zCFZdIx8d0gyIsw3Y"];
//3f58949f-e54d-4211-a735-e52cc0ab8f4d
// NSLog(#"%#",parameterString);
[request setHTTPMethod:#"GET"];
[request setURL:url];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//Even i apply push and set this data, nothing works!
// [request addValue:#"3f58949f-e54d-4211-a735-e52cc0ab8f4d" forHTTPHeaderField:#"oauth_consumer_key"];
// [request addValue:#"HMAC-SHA1" forHTTPHeaderField:#"oauth_signature_method"];
// [request addValue:#"1531983278" forHTTPHeaderField:#"oauth_timestamp"];
// [request addValue:#"cW1Xhs" forHTTPHeaderField:#"oauth_nonce"];
// [request addValue:#"1.0" forHTTPHeaderField:#"oauth_version"];
// [request addValue:#"pfZzKhniC9zCFZdIx8d0gyIsw3Y" forHTTPHeaderField:#"oauth_signature"];
// [request addValue:#"" forHTTPHeaderField:#"oauth_consumer_key"];
NSData *postData = [parameterString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postData];
NSData *finalDataToDisplay = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSMutableDictionary *abc = [NSJSONSerialization JSONObjectWithData: finalDataToDisplay
options: NSJSONReadingMutableContainers
error: &error];
How i can overcome this response issue ? Does anyone face similar issue ? Any idea to make work oauth 1.0 authentication in iOS Swift/Objective Project successfully ?
Related
For send data from POST method using windows azure mobile service .
Getting response error response
message = "An error has occurred."
My post method is and
data dictionary is
NSDictionary *data = #{#"emailID": #"abc#gmail.comt",
#"userPhone": #"",
#"password": #"12345678",
#"id":#"",
#"signUpBy": [NSNumber numberWithInt:1]};
And API call function is is
-(void)signUpCallAPI:(NSDictionary *)parameter{
// URL that calls into the Azure Service
NSString *serviceUri = #"https://demo.azure-mobile.net/tables/SignUp";
// Convert to NSURL type
NSURL *myURL = [NSURL URLWithString:serviceUri];
// Create a request object
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60];
NSError *error;
NSData *jsonData = nil;
if (parameter)
jsonData = [NSJSONSerialization dataWithJSONObject:parameter
options:NSJSONWritingPrettyPrinted
error:&error];
// Modify http headers for POST request
[request setHTTPMethod: #"POST"];
//Content type what we are sending
[request setValue:[NSString stringWithFormat:#"%lu",(unsigned long)jsonData.length ] forHTTPHeaderField:#"content-length"];
// Indicate JSON Data Format
[request setValue:#"application/json" forHTTPHeaderField:#"content-type"];
// Indicate JSON Data Format
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// Indicate host property
[request setValue:#"demo.azure-mobile.net" forHTTPHeaderField:#"Host"];
// Indicate application key (you get this from the portal)
[request setValue:#"demoappkey" forHTTPHeaderField:#"X-ZUMO-APPLICATION"];
//add data to body
[request setHTTPBody:jsonData];
// Execute request
conn= [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];}
For Post data from signup api not working .
Anything need to do my side?
Any sample available for for post data using API.
Thanks in advance
Looks like you're trying to use Mobile Services without using the iOS SDK. Microsoft has created an SDK for various mobile platform that simplify sending and retrieving data from Mobile Services: https://github.com/Azure/azure-mobile-services
I'd suggest you first look at the ToDo sample iOS app: https://azure.microsoft.com/en-us/documentation/articles/mobile-services-ios-get-started/
Next, this article in the Microsoft documentation explains how to add Mobile Services to an existing app: https://azure.microsoft.com/en-us/documentation/articles/mobile-services-ios-get-started-data/
I am creating an app in which I have to use paypal payment, after successful payment I have to generate payment detail, so I need access token.
I get the method how to get access token, I tried in hurl. It and I successfully get that access token using Client ID and Client Secret. Till this there is no problem.
But when I put those credentials (Client_ID and Client_Secret) in my code it always returns with invalid client credential.
NSURL *URL = [NSURL URLWithString:#"https://api.sandbox.paypal.com/v1/oauth2/token"];
// NSURLRequest *request = [NSURLRequest requestWithURL:URL
// cachePolicy:NSURLRequestUseProtocolCachePolicy
// timeoutInterval:30.0];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:URL];
NSString *client_id = #"xxxxxxxxxxxxxx";
NSString *client_secret = #"xxxxxxxxxxxxxx";
[request setHTTPMethod:#"POST"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", client_id, client_secret];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodingWithLineLength:80]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"en_US" forHTTPHeaderField:#"Accept-Language"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"client_credentials",#"grant_type", nil];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
request.HTTPBody = jsonData;
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Below is the log I prints in didFinishLoading
2015-07-14 14:54:25.130 paypalNativeDemo[1478:61010] {"error":"invalid_client","error_description":"Invalid client credentials"}
Sandbox credentials are different than live. Make sure you're using your sandbox client_id if you are talking to sandbox.
Generally this error is due to the REST app not yet being approved. I would suggest contacting PayPal Support through the number in your account and advise the agent that you are calling to check the status of your REST app.
For Android, I've been able to send POST requests in the following way:
HttpClient http = new DefaultHttpClient();
HttpPost request = new HttpPost("https://somewebsite.com");
request.setEntity(new StringEntity(data));
http.execute(request);
However, on iOS I get the following error:
NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9843)
What is the best way to perform a synchronous POST request using https on iOS?
You can try this function:
-(NSData *)post:(NSString *)postString url:(NSString*)urlString{
//Response data object
NSData *returnData = [[NSData alloc]init];
//Build the Request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
//Send the Request
returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
//Get the Result of Request
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
bool debug = YES;
if (debug && response) {
NSLog(#"Response >>>> %#",response);
}
return returnData;
}
And here is how you use it:
NSString *postString = [NSString stringWithFormat:#"param=%#",param];
NSString *urlString = #"https://www.yourapi.com";
NSData *returnData = [self post:postString url:urlString];
Edit:
I found the error code in the source code:
errSSLHostNameMismatch = -9843, /* peer host name mismatch */
The problem should be address on your server.
And here is from the docs:
errSSLHostNameMismatch -9843 The host name you connected with does
not match any of the host names allowed by the certificate. This is
commonly caused by an incorrect value for the kCFStreamSSLPeerName
property within the dictionary associated with the stream’s
kCFStreamPropertySSLSettings key. Available in OS X v10.4 and later.
hope this help
I came to the last stage of development of my app and here is the bit that I've never done before.
My friend has developed and API for my app to send and receive data, using django rest framework.
I need to authenticate my app to connect to it, send some data and receive data.
What I have found so far is:
NSURL *url = [NSURL URLWithString:#"http://localhost:8080/my/path/to/api/login/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"myUsername", #"myPassword"];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", authData];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
//------------------------------------------------------------------------------------------------------------------------------------//
//EDIT: Added this based on answer form #Quver.
NSURLResponse *response1;
NSError *responseError;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response1 error:&responseError];
if (result.length > 0 && responseError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:result
options:0
error:NULL];
NSLog(#"Got response form server: %#", greeting);
}
This equals output like:
<0a0a3c68 746d6c3e 0a0a2020 20203c68 6561643e 0a202020 20202020 200a2020 20202020 20200a20 20202020 + ~50 lines of similar stuff. Hope this helps.
//-----------------------------------------------------------------------------------------------------------------------------------------//
I guess this is the way to create request. What should I do next? And how do I know that I have connected?
Then, if I have connected, how do I get data form there? (I have a url that gives me json as output - this is what I want to get). Assume the url to be http://localhost:8080/url/that/gives/json/.
Thank you for any help. Hope this is enough information for the question. I will add anything else required.
NSURLResponse *response;
NSError *responseError;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&responseError];
Add this to get response. You already prepared request, now it's time to send it with NSURLConnection. I you sync request insted of async, becouse of using GCD for whole metod request + sqlite update.
After a few days of searching I have found a way.
First, we need a token for authentication. I am generating it through terminal for now:
curl -X POST -d "grant_type=password&username=<your username>&password=<your password>" http://<client secret>:<client id>#url/to/token/page
Then, in your view controller where you want to connect:
//always put </> at the end of link
NSURL *aUrl = [NSURL URLWithString: #"http://where/you/trying/to/conect"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request addValue:[NSString stringWithFormat:#"<type> <your token>"] forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
NSError *error = nil;
self.response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error: &error];
This will return any json that the page supposed to return. This might not be the most secure way, but this is exactly what I need for now. I will look at more secure solutions like OAuth 2, later.
Hope this helps to someone.
When I had used following code, I got the message "Failed to validate oauth signature and token"
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://api.twitter.com/oauth/access_token"]];
[request setHTTPMethod:#"POST"];
NSString *postString = #"oauth_consumer_key=My Consumer key&oauth_signature_method=HMAC-SHA1&oauth_signature=My Consumer secret&oauth_timestamp=?????&oauth_nonce=?????oauth_version=1.0&x_auth_username=My Twitter ID&x_auth_password=My Twitter password&x_auth_mode=client_auth";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSHTTPURLResponse *response = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *responseDataString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"Response from Twitter: %#", responseDataString);
So, I want to know exact configuration of request contents
The used post data as following. and My application had the ability to use xAuth
oauth_consumer_key=My Consumer key
oauth_signature_method=HMAC-SHA1
oauth_signature=My Consumer secret
oauth_timestamp=?????
oauth_nonce=?????
oauth_version=1.0
x_auth_username=My Twitter ID
x_auth_password=My Twitter password
x_auth_mode=client_auth
Read this. Hope it will help you.
https://dev.twitter.com/docs/oauth/xauth