I am working on UBER ride reminders api.i am trying to post ride reminder using my server_token.passing required parameter but in response i am getting 403 forbidden response. my http request is as follows.
NSDictionary *event=#{
#"time":event_time,
#"name":event_name
};
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:reminder.reminder_time forKey:#"reminder_time"];
[params setValue:reminder.phone_number forKey:#"phone_number"];
[params setValue:event forKey:#"event"];
NSString *url=#"https://api.uber.com/v1.2/reminders?server_token=***our server token***";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSError *error=nil;
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
NSURLResponse *response = nil;
[request addValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSData *authData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(!error && authData!=NULL)
{
NSError *jsonError = nil;
NSDictionary *authDictionary = [NSJSONSerialization JSONObjectWithData:authData options:0 error:&jsonError];
if(!jsonError && authDictionary !=nil)
{
NSLog(#"got respose");
}
else
{
NSLog(#"Error retrieving access token %#", jsonError);
}
}
else
{
NSLog(#"Error in sending request for access token %#", error);
}
and response object I am getting from this is as follows
<NSHTTPURLResponse: 0x600000029100> { URL: https://api.uber.com/v1.2/reminders?server_token=wMV7Y-ssag45YXzyTYZnYD7lCDNiBBKaG6Botcv7 } { status code: 403, headers {
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Type" = "application/json";
Date = "Thu, 06 Apr 2017 07:39:50 GMT";
Server = nginx;
"Strict-Transport-Security" = "max-age=604800";
"Transfer-Encoding" = Identity;
"X-Content-Type-Options" = nosniff;
"X-Uber-App" = "uberex-nonsandbox, optimus, migrator-uberex-optimus";
"X-XSS-Protection" = "1; mode=block";
} }
and json response is this
{
code = forbidden;
message = Forbidden;
}
I am trying to build mac osx application For UBER.I have completed all steps of Aouth2. I am successfully getting access_token. I am also able to retrieve user profile and history but while I am trying to post "ride request", I am getting 401 unauthorized error response.please help.Thank you In advance.
My code is as below.
**
//POST /v1/requests
NSString *sandBoxURL=#"https://sandbox-api.uber.com/v1";
NSString *url = [NSString stringWithFormat:#"%#/requests", sandBoxURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request addValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:[NSString stringWithFormat:#"Bearer %#", _accessToken] forHTTPHeaderField:#"Authorization"];
NSError *error = nil;
request.HTTPMethod = #"POST";
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
NSLog(#"Request for Product Request:%#",request);
[self performNetworkOperationWithRequest:request completionHandler:^(NSDictionary *requestDictionary, NSURLResponse *response, NSError *error)
{
NSLog(#"Response for Product Request:%#",response);
NSLog(#"Result:%#",requestDictionary);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300)
{ //OK
UberRequest *requestResult = [[UberRequest alloc] initWithDictionary:requestDictionary];
// handler(requestResult, response, error);
}
if (409 == httpResponse.statusCode) { //needs surge confirmation
NSLog(#"Surge Conflict");
}
else
{
NSLog(#"Error In response");
}
}];
**
And response I am getting is:
{ URL: https://sandbox-api.uber.com/v1/requests } { status code: 401, headers {
Connection = "keep-alive";
"Content-Length" = 83;
"Content-Type" = "application/json";
Date = "Mon, 07 Nov 2016 11:19:35 GMT";
Server = nginx;
"Strict-Transport-Security" = "max-age=0";
"X-Content-Type-Options" = nosniff;
"X-Uber-App" = "uberex-sandbox, migrator-uberex-sandbox-optimus";
"X-Uber-Missing-Scopes" = true;
"X-XSS-Protection" = "1; mode=block";
} }
Result:{
code = unauthorized;
message = "Requires at least one scope. Available scopes: ";
}
I got the solution. Problem Was With My Scope input.While requesting for token,even if the account you are login is of developer, we need put scopes properly. In my case I needed request scope in token.
I'm encrypting some text i want to send to a server and I have no problems encrypting it, and decrypting it in Objective-C but when I send it to the nodejs server the result by decrypting it never comes right the encrypted data comes always the same... I think the problem is how I use the crypto library, here's my Xcode code:
NSString * key =#"1234567890123456";
NSString * url = #"http://flystory.herokuapp.com/register";
NSString *post = #"hola mundo!!!!!!!!!!";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSLog(#"%#",[[NSString alloc] initWithData:postData encoding:NSASCIIStringEncoding]);
NSError *e;
CCCryptorStatus err;
postData = [postData dataEncryptedUsingAlgorithm:kCCAlgorithmAES128 key:key options:kCCOptionECBMode error:&err];
NSLog(#"%#",[[NSString alloc] initWithData:postData encoding:NSASCIIStringEncoding]);
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"post"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"body" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *r, NSData *d, NSError *e) {
if (e) NSLog(#"%#",e.description);
else [self handleRespondedData:d];
}];
postData = [postData decryptedDataUsingAlgorithm:kCCAlgorithmAES128 key:key options:kCCOptionECBMode error:&err];
NSLog(#"%#",[[NSString alloc] initWithData:postData encoding:NSASCIIStringEncoding]);
to encrypt I'm using this NSData extension contained in the NSData+CommonCrypto.h/m in https://github.com/Gurpartap/AESCrypt-ObjC
my Node.JS code goes as follows:
var express = require("express");
var app = express(express.bodyParser());
//...
app.post("*", function(request, response) {
var body = '';
request.setEncoding('hex');
request.on('data', function (data) {
body += data;
var crypto=require('crypto');
var decipher=crypto.createDecipher('aes-128-ecb', '1234567890123456');
decipher.setAutoPadding(auto_padding=false);
var enc = decipher.update(body, 'hex', 'utf8') + decipher.final('utf8');
console.log('encrypted: ' + body);
console.log('decrypted: ' + enc);
});
request.on('end', function () {
// use POST
route(handle, request.path, response, body);
});
});
What is nice and simple in C# is turning out to be a bear in Objective C
static private void AddUser(string Username, string Password)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://192.168.1.10:8080/DebugUser?userName=" + Username + "&password=" + Password));
request.Method = "POST";
request.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.Write(response.StatusCode);
Console.ReadLine();
}
works fine, but when I try and convert it to Objective-C (IOS), all I get is "Connection State 405 Method not allowed"
-(void)try10{
NSLog(#"Web request started");
NSString *user = #"me#inc.com";
NSString *pwd = #"myEazyPassword";
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",user,pwd];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%ld", (unsigned long)[postData length]];
NSLog(#"Post Data: %#", post);
NSMutableURLRequest *request = [NSMutableURLRequest new];
[request setURL:[NSURL URLWithString:#"http://192.168.1.10:8080"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection){
webData = [NSMutableData data];
NSLog(#"connection initiated");
}
}
Any help or pointers to using POST on IOS would be a great help.
Those requests are not exactly the same.
C# example sends POST request to /DebugUser with query params ?userName=<username>&password=<password>, obj-c one sends POST request to / with form-urlencoded data userName=<username>&password=<password>. I guess that problem is this small mistake in URI path (mostly those small, stupid mistakes takes more time to solve than real problems.. ;) ). Additionally I would suggest to url encode params, in this example your username me#inc.com should be encoded as me%40inc.com to be valid url/form-url encoded data. See also my code-comment about ivar.
Something like that should work (written on the fly, I haven't compile that / check before posting):
-(void)try10{
NSString *user = #"me%40inc.com";
NSString *pwd = #"myEazyPassword";
NSString *myURLString = [NSString stringWithFormat:#"http://192.168.1.10:8080/DebugUser?username=%#&password=%#",user,pwd];
NSMutableURLRequest *request = [NSMutableURLRequest new];
[request setURL:[NSURL URLWithString:myURLString]];
[request setHTTPMethod:#"POST"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection){
// I suppose this one is ivar, its safer to use #property
// unless you want to implement some custom setters / getters
//webData = [NSMutableData data];
self.webData = [NSMutableData data];
NSLog(#"connection initiated");
}
}
I have a php webpage that requires a login (userid & password). I have the user enter the information into the app just fine.. but I need an example on how to do a POST request to a website. The apple example on the support site is rather complicated showing a picture upload.. mine should be simpler.. I just want to post 2 lines of text..
Anyone have any good examples?
Alex
This is what I recently used, and it worked fine for me:
NSString *post = #"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.nowhere.com/sendFormHere.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
Originally taken from http://deusty.blogspot.com/2006/11/sending-http-get-and-post-from-cocoa.html, but that blog does not seem to exist anymore.
From Apple's Official Website :
// In body data for the 'application/x-www-form-urlencoded' content type,
// form fields are separated by an ampersand. Note the absence of a
// leading ampersand.
NSString *bodyData = #"name=Jane+Doe&address=123+Main+St";
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://www.apple.com"]];
// Set the request's content type to application/x-www-form-urlencoded
[postRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// Designate the request a POST request and specify its body data
[postRequest setHTTPMethod:#"POST"];
[postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
// Initialize the NSURLConnection and proceed as described in
// Retrieving the Contents of a URL
From : code with chris
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://google.com"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = #"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
ASIHTTPRequest makes network communication really easy
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:#"Ben" forKey:#"names"];
[request addPostValue:#"George" forKey:#"names"];
[request addFile:#"/Users/ben/Desktop/ben.jpg" forKey:#"photos"];
[request addData:imageData withFileName:#"george.jpg" andContentType:#"image/jpeg" forKey:#"photos"];
You can do using two options:
Using NSURLConnection:
NSURL* URL = [NSURL URLWithString:#"http://www.example.com/path"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
// Form URL-Encoded Body
NSDictionary* bodyParameters = #{
#"username": #"reallyrambody",
#"password": #"123456"
};
request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];
// Connection
NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil];
[connection start];
/*
* Utils: Add this section before your class implementation
*/
/**
This creates a new query parameters string from the given NSDictionary. For
example, if the input is #{#"day":#"Tuesday", #"month":#"January"}, the output
string will be #"day=Tuesday&month=January".
#param queryParameters The input dictionary.
#return The created parameters string.
*/
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
NSMutableArray* parts = [NSMutableArray array];
[queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
NSString *part = [NSString stringWithFormat: #"%#=%#",
[key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
[value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
];
[parts addObject:part];
}];
return [parts componentsJoinedByString: #"&"];
}
/**
Creates a new URL by adding the given query parameters.
#param URL The input URL.
#param queryParameters The query parameter dictionary to add.
#return A new NSURL.
*/
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
NSString* URLString = [NSString stringWithFormat:#"%#?%#",
[URL absoluteString],
NSStringFromQueryParameters(queryParameters)
];
return [NSURL URLWithString:URLString];
}
Using NSURLSession
- (void)sendRequest:(id)sender
{
/* Configure session, choose between:
* defaultSessionConfiguration
* ephemeralSessionConfiguration
* backgroundSessionConfigurationWithIdentifier:
And set session-wide properties, such as: HTTPAdditionalHeaders,
HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
*/
NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
/* Create session, and optionally set a NSURLSessionDelegate. */
NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
/* Create the Request:
Token Duplicate (POST http://www.example.com/path)
*/
NSURL* URL = [NSURL URLWithString:#"http://www.example.com/path"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
// Form URL-Encoded Body
NSDictionary* bodyParameters = #{
#"username": #"reallyram",
#"password": #"123456"
};
request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];
/* Start a new Task */
NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil) {
// Success
NSLog(#"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode);
}
else {
// Failure
NSLog(#"URL Session Task Failed: %#", [error localizedDescription]);
}
}];
[task resume];
}
/*
* Utils: Add this section before your class implementation
*/
/**
This creates a new query parameters string from the given NSDictionary. For
example, if the input is #{#"day":#"Tuesday", #"month":#"January"}, the output
string will be #"day=Tuesday&month=January".
#param queryParameters The input dictionary.
#return The created parameters string.
*/
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
NSMutableArray* parts = [NSMutableArray array];
[queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
NSString *part = [NSString stringWithFormat: #"%#=%#",
[key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
[value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
];
[parts addObject:part];
}];
return [parts componentsJoinedByString: #"&"];
}
/**
Creates a new URL by adding the given query parameters.
#param URL The input URL.
#param queryParameters The query parameter dictionary to add.
#return A new NSURL.
*/
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
NSString* URLString = [NSString stringWithFormat:#"%#?%#",
[URL absoluteString],
NSStringFromQueryParameters(queryParameters)
];
return [NSURL URLWithString:URLString];
}
I am a beginner in iPhone apps and I still have an issue although I followed the above advices. It looks like POST variables are not received by my server - not sure if it comes from php or objective-c code ...
the objective-c part (coded following Chris' protocol methodo)
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://example.php"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [NSString stringWithFormat:#"user_name=%#&password=%#", self.userNameField.text , self.passwordTextField.text];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
//NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSLog(#"Response: %#",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
Below the php part :
if (isset($_POST['user_name'],$_POST['password']))
{
// Create connection
$con2=mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// retrieve POST vars
$username = $_POST['user_name'];
$password = $_POST['password'];
$sql = "INSERT INTO myTable (user_name, password) VALUES ('$username', '$password')";
$retval = mysqli_query( $sql, $con2 );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysqli_close($con2);
}
}
else
{
echo "No data input in php";
}
I have been stuck the last days on this one.
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:#"name" forKey:#"email"];
[contentDictionary setValue:#"name" forKey:#"username"];
[contentDictionary setValue:#"name" forKey:#"password"];
[contentDictionary setValue:#"name" forKey:#"firstName"];
[contentDictionary setValue:#"name" forKey:#"lastName"];
NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonStr);
NSString *urlString = [NSString stringWithFormat:#"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:#"moinsam" password:#"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];
Thanks a lot it worked , please note I did a typo in php as it should be mysqli_query( $con2, $sql )
Here i'm adding sample code for http post print response and parsing as JSON if possible, it will handle everything async so your GUI will be refreshing just fine and will not freeze at all - which is important to notice.
//POST DATA
NSString *theBody = [NSString stringWithFormat:#"parameter=%#",YOUR_VAR_HERE];
NSData *bodyData = [theBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//URL CONFIG
NSString *serverURL = #"https://your-website-here.com";
NSString *downloadUrl = [NSString stringWithFormat:#"%#/your-friendly-url-here/json",serverURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: downloadUrl]];
//POST DATA SETUP
[request setHTTPMethod:#"POST"];
[request setHTTPBody:bodyData];
//DEBUG MESSAGE
NSLog(#"Trying to call ws %#",downloadUrl);
//EXEC CALL
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Download Error:%#",error.description);
}
if (data) {
//
// THIS CODE IS FOR PRINTING THE RESPONSE
//
NSString *returnString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(#"Response:%#",returnString);
//PARSE JSON RESPONSE
NSDictionary *json_response = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
if ( json_response ) {
if ( [json_response isKindOfClass:[NSDictionary class]] ) {
// do dictionary things
for ( NSString *key in [json_response allKeys] ) {
NSLog(#"%#: %#", key, json_response[key]);
}
}
else if ( [json_response isKindOfClass:[NSArray class]] ) {
NSLog(#"%#",json_response);
}
}
else {
NSLog(#"Error serializing JSON: %#", error);
NSLog(#"RAW RESPONSE: %#",data);
NSString *returnString2 = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(#"Response:%#",returnString2);
}
}
}];
Hope this helps!