Reputation:
I've come across something new to me, and a little confused how to approach it. I need to login to a webserver, up until now I just do it the normal way sending details to a php script and its been great.
I've started working with a new guys today, and it seems things are different, I'm no longer talking to a php script but what looks like to be directly to JSON. The guy showed me how to login via some php code.
$loginParams = array();
$loginParams[username] = "[email protected]";
$loginParams[password] = "password";
print "<li>CALLING login.json";
$request = new RestRequest('http://'.$SERVER.'/api/login.json', 'POST', $loginParams);
$request->execute();
Now i want to mimic that with Objective-C.
Is he sending JSON to the JSON page?
How can I remake that in objective-c?
Many Thanks -Code
Upvotes: 0
Views: 229
Reputation: 129
Hmmm. Without seeing specifics on their service it looks like they may just be posting the username and password to the service and RETURNING JSON.
Try some code like this and see if it works:
NSString *postString = [NSString stringWithFormat:@"username=%@&password=%@", username, password];
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:YourURLObject];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
You'll then need to process the response. Again, I am not sure now that RestRequest is being used so this is just a guess on my part.
Upvotes: 0
Reputation: 12036
You could use something like this
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"[email protected]" forKey:@"username"];
[request setPostValue:@"password" forKey:@"password"];
[request startSynchronous];
NSError *localError = [request error];
NSLog(@"Error:%@",[localError description]);
if(!localError){
NSString *response = [request responseString];
NSLog(@"Response:%@",response);
}
ASIHTTPRequest docs.
Upvotes: 2