我正在尝试通过从我的iOS应用程序向php脚本发送POST请求来验证用户身份。然后让iOS应用程序读取NSHTTPURLResponse以确定它是否成功。我的iOS代码如下所示,由于某种原因,它说我的NSURLConnection未使用。 int代码总是返回值为200。
- (void)authenticateUser:(NSString *)aUsername
password:(NSString *)aPassword
{
NSString *post = [NSString stringWithFormat:@"username=%@&pw=%@", aUsername, aPassword];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [post length]];
NSURL *url = [NSURL URLWithString:@"http://XXX.com/query-db.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int code = [httpResponse statusCode];
// Log the response
NSLog(@"%d", code);
if(code == 1){
NSLog(@"received a 1");
[self updateWorkTime];
//[self close];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Unsuccessul Attempt" message:@"The username or password is invalid, please try again." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
另外,如果你想看看我的php脚本,我在虚拟变量中输入并测试它是否正确查询数据库并检查出来...但是以防你好奇。
<?php
$sentUsername = $_POST['username'];
$sentPW = $_POST['pw'];
mysql_connect("xxx", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$result = mysql_query("SELECT * FROM Table") or die(mysql_error());
$authenticate = 0;
while($authenticate == 0) {
$row = mysql_fetch_array($result);
$selectedUsername = $row['username'];
$selectedPW = $row['pw'];
$pwComp = strcmp($sentPW, $selectedPW);
$userComp = strcmp($selectedUsername, $sentUsername);
if(!$row) break;
if($selectedPW == $sentPW && $selectedUsername == $sentUsername) {
$authenticate = 1;
}
}
echo $authenticate;
?>
我尝试设置PHP标头,但我不确定如何做到这一点。我感谢这个社区给予我的任何和所有帮助,真正无价之宝。谢谢!
答案 0 :(得分:2)
您收到的'200'代码是HTTP状态代码,表示请求成功。
如果您正在从PHP脚本发回“1”或“0”值之后,您应该使用didReceiveData:
委托方法,而不是didReceiveResponse:
来查找它。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
NSLog(@"authenticate value => %@",[[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding]);
}
答案 1 :(得分:0)
您正在使用NSASCIIStringEncoding - 尝试使用NSUTF8StringEncoding - 您可能会在转换为NSData对象时丢失它。
此外,您应该使用HTTPS,否则您的密码对所有人都可见: - )