xcode using json and POST to validate a username and password - ios

I am new to using POST, and have just written a code that takes a username and password that was entered in and sends it via POST for validation. If it is valid, it will return true, if not it will return false. I think my code works for the most part, but there must be something missing with my return data because it does not output true or false. Here is my code:
- (IBAction)btnLogIn:(id)sender;
{
//getting the username and password and putting it into a string
NSString *post =[[NSString alloc] initWithFormat:#"username= %# &password =%#",[self.lblUserName text],[self.lblPassword text]];
//output the string
NSLog(#"PostData: %#",post);
//setting the URL to post to
NSURL *url=[NSURL URLWithString:#"myurl.php"];
//converts string to data that can be used to post
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//get the length of the string
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
//formatting the URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
}
I am not sure what part is missing or wrong. Everything runs fine, just returns blank when I test it out.

this is another method
//Create the request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"myurl.php"]];
// create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server
NSString *userUpdate =[NSString stringWithFormat:#"username=%#&password=%#",[self.lblUserName text],[self.lblPassword text],nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}

Related

"+" replaced by " " in json send to server

NSString *AuthToken = [[NSUserDefaults standardUserDefaults]
stringForKey:#"AuthToken"];
NSString* json =[NSString stringWithFormat:#"{'DeviceId':'%#','DeviceType':'iOS','UM_Identifier':'%#','AuthToken':'%#','Query':'all'}", deviceId, userEmail, AuthToken];
NSString *post =[[NSString alloc] initWithFormat:#"jinpAllCustDetails=%#",json];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://www.google.com"]];
NSData *postData = [post dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
In above code :
Auth token received from last webservice response is saved in NSUserdefaults,
then used for next webservice request.
So for Eg.
Send auth token : z71VxyfVlBxvNKJ01m64a4oKV9lWEv+fFhHxi+7zyRw=
But server would receives it as :z71VxyfVlBxvNKJ01m64a4oKV9lWEv fFhHxi 7zyRw=
ie All occurrences of "+" are replaced by " ". So server considers it as an invalid auth token and the webservices request returns a result accordingly.
Help me to fix this, thanks in advance
That isn't valid JSON as strings should be surrounded with ". Create an NSDictionary of the values and use NSJSONSerialization to create the JSON string, which you know will be valid:
NSDictionary *values = #[
#"DeviceId": deviceId,
#"DeviceType": #"iOS",
#"UM_Identifier": userEmail,
#"AuthToken": authToken,
#"Query": #"all"
];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:values
options:0
error:&error];
NSAssert(jsonData != nil, #"Failed to create JSON data");
NSString jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];

Http Post parameters to url don't send special characters "+" in objectC Xcode

I have create an application that send two POST parameters to aspx server and it's save data in database.
It's an Iphone Application.
Here's the code:
NSString *post = [NSString stringWithFormat:#"name=%#&number=%#",
name,number];
NSString *capturedpost = [post
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *postData = [capturedpost dataUsingEncoding:NSUTF8StringEncoding];
//NSString *postLength = [NSString stringWithFormat:#"%d", [postData
length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http:/www.myurl.aspx"]];
[request setHTTPMethod:#"POST"];
//[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//[request setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request
returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler
bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
But on server, the string "number" that contain the telephone number like "+393333..." save in db the number without the "+".
How can I do?
The server side works fine, because the same App on Android that do same request work perfect!
OK, thanks to "holex" I successfully encode the URL in this way:
NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)post,
NULL,
(CFStringRef)#"+",
kCFStringEncodingUTF8 ));
And the "+" saved correctly in db!

HTTP request GET response showing NULL value

I want to create HTTP request post and get response by using simple Objective C Code method. Here below code to I can post successfully. But I didn't receive response data's. Response printing null value only. Please help me, I need to get response data's.
Here below my code
NSString *post = [NSString stringWithFormat:#"name=%#",name];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:URLPATH]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}
// Create GET method
NSError *err;
NSURLResponse *responser;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responser error:&err];
// JSON Formatter
NSError *error;
NSDictionary *jsonsDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *respon = [jsonsDictionary objectForKey:#"response"];
NSLog(#"UPDATE RESPONSE : %#", respon);
You's data post is NSString *post = [NSString stringWithFormat:#"name=%#",name]; . So in this case you need set request header "Content-Type" to "application/x-www-form-urlencoded" or use following code to convert string to data and set Content-Type header:
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
...
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
Its very simple:
//-- Convert string into URL
NSString *jsonUrlString = [NSString stringWithFormat:#"demo.com/your_server_db_name/service/link"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Send request to server
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
//-- Send username & password for url authorization
[request setValue: jsonUrlString forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"]; //-- Request method GET/POST
//-- Receive response from server
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//-- JSON Parsing with response data
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Result = %#",result);
Sample : https://github.com/svmrajesh/Json-Sample

How to send raw data to API

I have one text field I need to send two data's to API.
NSString *post =[NSString stringWithFormat:#"val1=%#,val2=%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"val1"],val2];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://api.test.com/send"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"log%#",str);
}
I need to send only raw data to API this is my code.Please check and let me know thanks
NSData *postData = [someStringToPost dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:someURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
if (error)
{
//error
}
else
{
//no error
}
Try this
Have you tried converting it to NSData and sending that?
Here's the conversion:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
That will give you the data in bytes, then just pass it in with the normal networking function calls.

unsupported URL error code -1002

Hi Please help me how to prepare NSMutableURLRequest for below api
URL : www.XXXXXXXX.com/api.php
For Login :-
www.XXXXXXXXXXXX.com/api.php?task=login
POST Data :-
"email" => User's email
"pw" => User's Password
json response: session id on successful login
Am trying like this.
NSMutableURLRequest *request;
request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"www.XXXXXXXX.com/api.php?task=login"]];
[request setHTTPMethod:#"POST"];
NSString *postString =#"email=xxxxxxxx#gmail.com&pw=1234";
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
One reason could be that you forgot to add the "http:" scheme:
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.XXXXXXXX.com/api.php?task=login]];
HERE --^
Note also that the correct way to set body data and in particular the length is
NSString *postString =#"email=xxxxxxxx#gmail.com&pw=1234";
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:postData];
because the length of the UTF-8 encoded data can be different from the (Unicode) string length.
I ran into this error when I specified my base URL with a variable that accidentally contained a new line.
Try this:
NSError *error;
NSString *jsonString;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonData1
options:0 error:&error];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSData *postData = [[[NSString alloc] initWithFormat:#"method=methodName&email=%#&password=%#", user_name, pass_word] dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%ld",[postData length]];
jsonData=[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Accept\""];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Content-Type\""];
[request setValue:postLength forHTTPHeaderField:#"\"Content-Length\""];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSError *requestError = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&requestError];
if ([response statusCode] >= 200 && [response statusCode] < 300) {
NSError *serializeError = nil;
NSString* newStr = [NSString stringWithUTF8String:[urlData bytes]];
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments
error:&serializeError];
NSLog(#"recdata %#",jsonData);
}
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
NSLog(#"theConnection is succesful");
}
[connection start];

Resources