我是使用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);
}
我不确定哪个部分缺失或错误。一切都运行正常,当我测试它时只返回空白。
答案 0 :(得分:1)
这是另一种方法
//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");
}