Getting Request Token From Dropbox OAuth "Invalid OAuth Request" - oauth

I'm trying to get a response data from dropbox oauth as described here
Now i dont know why it keeps saying {"error": "Invalid OAuth request."}
Here is a my complete code for requesting token:
-(void)requestTokenSecret
{
NSString* oauthVersion=#"1";
NSString* oauth_signature_method=#"PLAINTEXT";
NSString* postHeader = [NSString stringWithFormat: #"Authorization: OAuth oauth_version=\"%#\", oauth_signature_method=\"%#\", oauth_consumer_key=\"%#\", oauth_signature=\"%#&\"",oauthVersion,oauth_signature_method,APP_KEY,APP_SECRET];
NSLog(#"URL HEADER: %#",postHeader);
NSData* postHeaderData = [postHeader dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest* request= [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"https://api.dropbox.com/1/oauth/request_token"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d",[postHeaderData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postHeaderData];
NSURLConnection* conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];
if(conn)
{
NSLog(#"Connected");
}
else
NSLog(#"Connected");
}

It looks like you're putting "Authorization: OAuth ..." in the body of the POST request instead of putting "OAuth ..." in the Authorization header.
Give this code a try instead (untested, sorry):
NSString* oauthVersion=#"1";
NSString* oauth_signature_method=#"PLAINTEXT";
NSString* authorizationHeader = [NSString stringWithFormat: #"OAuth oauth_version=\"%#\", oauth_signature_method=\"%#\", oauth_consumer_key=\"%#\", oauth_signature=\"%#&\"",oauthVersion,oauth_signature_method,APP_KEY,APP_SECRET];
NSMutableURLRequest* request= [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"https://api.dropbox.com/1/oauth/request_token"]];
[request setHTTPMethod:#"POST"];
[request setValue:authorizationHeader forHTTPHeaderField:#"Authorization"];
NSURLConnection* conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];
Also, I would strongly suggest using OAuth 2 instead of OAuth 1. It's considerably simpler.

Related

Sending Post http request from nsstring

I have this json:
{"myFriends":{"userId":"the user id", "userName":"the user name", "friends":[{"u":"friend user id","n":"friend user name"},{"u":"friend user id","n":"friend user name"}]}}
and I want to send him in post request to the server, this is the current way I am trying to do this:
+(NSData *)postDataToUrl:(NSString*)urlString :(NSString*)jsonString
{
NSData* responseData = nil;
NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSString *bodydata=[NSString stringWithFormat:#"%#",jsonString];
[request setHTTPMethod:#"POST"];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPBody:req];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"the final output is:%#",responseString);
return responseData;
}
The json string contains the json, but for some reason the server always get nil and return error. How to fix this?
It would certainly help to tell your server about the content type:
[request addValue:#"application/json"
forHTTPHeaderField:#"Content-Type"];
Furthermore: in my own code I use:
[request setHTTPBody:[bodydata dataUsingEncoding:NSUTF8StringEncoding]]
This is my code for POST request with an NSData parameter:
- (void)uploadJSONData:(NSData*)jsonData toPath:(NSString*)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kRequestTimeout];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: data];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[data length]] forHTTPHeaderField:#"Content-Length"];
// Create url connection and fire request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
}
This is for an asynchronous request, but it should work just fine for synchronous. The only thing I see you might be missing is the "Content-Length" parameter.

Posting to a Google Forms form using NSURLRequest

I am trying to post a string to a Google Form using NSURLRequest. The method seems to be getting called, but the post to the Google Form doesn't appear. This is the code I am using:
NSURL *requestURL = [NSURL URLWithString:#"https://docs.google.com/forms/d/1T9M6B_k4tiQcSPP5iS2jyU7DCkoRC1jFVql_eQDy9ek/formResponse"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request setHTTPMethod:#"POST"];
NSString *postString = #"entry.757751040=Test sent from iOS App";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
if (connection){
NSLog(#"Connecting...");
}
I created this form solely for testing purposes. "Connecting..." gets logged, so I know the connection is being made, but the string does not appear in the Google Forms Spreadsheet. Am I doing something wrong? Any help would be greatly appreciated.
This piece of code only checks if connection is not nil
if (connection){
NSLog(#"Connecting...");
}
is equivalent to
if (connection != nil){
NSLog(#"Connecting...");
}
As such, it has nothing to do with an actual connection to the URL.
The method initWithRequest:(NSURLRequest *)request delegate:(id)delegate which you are using will perform the request immediately. This means that you have to perform the operations in another order if you want your params to work:
NSURL *requestURL = [NSURL URLWithString:#"https://docs.google.com/forms/d/1T9M6B_k4tiQcSPP5iS2jyU7DCkoRC1jFVql_eQDy9ek/formResponse"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *postString = #"entry.757751040=Test sent from iOS App";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Along with this, consider implementing NSURLConnectionDelegate.

NSURLRequest not posting values to a Codeigniter API

Good day,
I am trying to use a Codeigniter based API to connect with iOS and using NSURLRequest.
The API is in debugMode and for now it returns the same key value pair as json as the one that you are posting. I have tried posting the values to the link through postman and it works correctly, however when I post it through my iOS application, the json response is received but the array that should contain the post values is empty.
Here is the iOS Code snippet :
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BASEURL,service]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSString * params = #"authkey=waris";
NSData * postData = [params dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSLog(#"Posting : '%#' to %#",params,url);
[connection start];
This is the response when I post the same parameters through postman ( A RESTFUL Client for Chrome )
{
"status": "1",
"data": {
"authkey": "warisali"
}
}
However when I query the same API from the above iOS Code I am getting this :
{
data = 0;
status = 1;
}
Any help on the matter will be highly appreciated!
I had same issue (not with CodeIgniter but with Ruby ...)
Try something like this, solved my problem.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BASEURL,service]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSDictionary *paramDict = #{#"authkey": #"waris"};
NSError *error = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:paramDict options:NSJSONWritingPrettyPrinted error:&error];
if (error)
{
NSLog(#"error while creating data %#", error);
return;
}
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSLog(#"Posting : '%#' to %#",params,url);
[connection start];
I ended up using the ASIHttpRequest + SBJson combo and that worked like Charm!
After adding the ASIHttpRequest core classes and SBJson Classes to parse the JSON, I was able to achieve what I wanted !
The problem is that because of the way you're creating the connection, it will start immediately, before you've finished configuring the request. Thus, you're creating a mutable request, creating and starting the connection, then attempting to modify the request and then trying to start the request a second time.
You can fix that by changing the line that says:
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
To say:
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
Or, easier, just move the original instantiation of the NSURLConnection (without the startImmediately:NO) after you've finished configuring your request, and then eliminate the [connection start] line altogether.

Web services for iOS application with C# using mysql?

I am working on iPhone application with web services.
Using HTTP POST method I tried post the data. But data is saving in database. The response I'm getting is 404 or 400. here C# is used instead of PHP.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#""]];
NSString *userUpdate =[NSString stringWithFormat:#"Name=%#,FirstName=%#,DateofBirth=%#,Sex=%#,Country=%#,City=%#,PhoneNumber=%#,IncumbentonPremimum=%#",Name,FirstName,DateofBirth,Sex,Country,City,PhoneNumber,IncumbentonPremimum];
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
NSString *postLength = [NSString stringWithFormat:#"%d",[data1 length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:data1];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);`

HTTPost setEntity equivalent in iOS

I have an android application which communicates to the server through HTTP Post.
Here is the code and url_select is "http://example.com/Padua/rest/messages/messagetodelete"
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost post = new HttpPost(url_select);
post.setEntity(new ByteArrayEntity(message.toString().getBytes("UTF8")));
HttpResponse response = client.execute(post);
This works well and I am able to get the message in the server. But when I try implementing this in iphone I am struck. I am not sure how to accomplish this. In Exact, the setentity part in NSMutalbleURLRequest
Below is the code
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[NSURL URLWithString:#"http://example.com/Padua/rest/messages/messagetodelete"];
[request setURL:[NSURL URLWithString:#"http://example.com/Padua/rest/messages/messagetodelete"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
//This is where I am getting confused. How to pass the messageid to the URL??
[request setHTTPBody:messageid];
//This is where I am getting confused
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:messageid
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Can any one please help me. I need to pass on the messageid in the URL itself in iOS as in Android.
Thanks and if you need any addtional info, I will provide you

Resources