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");
}
}