简体   繁体   English

Objective-C中的HTTP发布不发布任何内容

[英]HTTP Post in objective-c doesn't post anything

I have the code below which runs fine but doesn't appear to post anything, or at least my php doesn't pick it up. 我有下面的代码,它运行正常,但似乎没有张贴任何东西,或者至少我的php没有接它。 What am I doing wrong? 我究竟做错了什么?

Here's my php: 这是我的PHP:

$usr = $_POST['username'];
$psw = $_POST['password'];
if ($usr == '1' && $psw == '1') {
    echo 'Yes';
}

And here's my objective-c 这是我的目标

NSString *post =[NSString stringWithFormat:@"username=%@&password=%@",usernameField.text, passwordField.text];

NSString *hostStr = @"http://ep.samico.dk/blogapp/login.php?";
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL =  [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];    
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
if([serverOutput isEqualToString:@"Yes"]){
    UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"success" message:@"You are authorized"
                                                          delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
    [alertsuccess show];

} else {
    UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Fail" message:@"Invalid Access"
                                                          delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
    [alertsuccess show];

}

Going off what was said in the comments: 摆脱评论中所说的:

The below section (your code) generates the URL string with the parameters added to the end of it. 以下部分(您的代码)将生成URL字符串,并在其末尾添加参数。

NSString *post =[NSString stringWithFormat:@"username=%@&password=%@",usernameField.text, passwordField.text];

NSString *hostStr = @"http://ep.samico.dk/blogapp/login.php?";
hostStr = [hostStr stringByAppendingString:post];

You can either modify this to actually do a POST or you can modify your PHP code to handle them as a GET instead of a POST. 您可以修改它以实际执行POST 也可以修改PHP代码以将它们作为GET(而不是POST)来处理。

$usr = $_GET['username'];
$psw = $_GET['password'];
if ($usr == '1' && $psw == '1') {
    echo 'Yes';
}

To do a POST in objc, you need to use NSURLConnection directly, like the following: 要在objc中执行POST,您需要直接使用NSURLConnection ,如下所示:

NSString *post = [NSString stringWithFormat:@"username=%@&password=%@", @"username", @"pass"];

NSString *hostStr = @"http://ep.samico.dk/blogapp/login.php?";
NSURL *hostURL = [NSURL URLWithString:hostStr];
NSMutableURLRequest *req  = [NSMutableURLRequest requestWithURL:hostURL];
[req setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];

NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];

NSString *contents = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM