xcode使用json和POST验证用户名和密码



我是使用POST的新手,刚刚编写了一个代码,该代码接受输入的用户名和密码,并通过POST发送以进行验证。如果它是有效的,它将返回true,否则它将返回false。我认为我的代码在大多数情况下都是有效的,但我的返回数据肯定缺少一些东西,因为它不会输出true或false。这是我的代码:

- (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);

}

我不确定哪一部分缺了或错了。一切运行良好,只是在测试时返回空白。

这是的另一种方法

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

最新更新