iPhone-PHP发布请求


iPhone - PHP Post Request

这是我的第一个问题,我希望能得到一些帮助:

我使用了几种方法(并尝试使用不同的http传输框架)对localhost中的php脚本进行后期操作,但没有取得好的结果。我不知道还能找什么。我已经被这个问题困扰了至少6或7个小时,最终得到了这个:

目标C代码:

if (name != nil && message != nil) {
        NSMutableString *postString = [NSMutableString stringWithString:TFPostURL];
        [postString appendString:[NSString stringWithFormat:@"%@=%@",TFName,name]];
        [postString appendString:[NSString stringWithFormat:@"%@=%@",TFMessage,message]];
        [postString setString:[postString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];
        [request setHTTPMethod:@"POST"];
        postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

    }

TFPostURL、TFName、TFMessage、name和message是我定义的常量。

我使用数据库只是为了检查传输是否成功:

PHP脚本

<?php
$username = "root";
$database = "db";
mysql_connect(localhost, $username);
@mysql_select_db($database) or die("Unable to find database");
$name = $_POST["name"];
$message = $_POST["message"];
$query = "INSERT INTO test VALUES ('', '$name', '$message')";
mysql_query($query) or die(mysql_error("error"));
mysql_close();
?>

有什么想法会出错吗?

我一直在本地主机上尝试,还需要在另一个mac上尝试。我正在将我的php文件上传到公共域,并检查它是否在我自己的计算机中。


编辑

我已经将PHP POST操作更改为GET,获得了惊人的结果;现在它工作了!

<?php
$username = "root";
$database = "db";
mysql_connect(localhost, $username);
@mysql_select_db($database) or die("Unable to find database");
$name = $_GET["name"];
$message = $_GET["message"];
$query = "INSERT INTO test VALUES ('', '$name', '$message')";
mysql_query($query) or die(mysql_error("error"));
mysql_close();
?>

我建议使用ASIHTTP库。他们非常优秀。下面是一些示例代码:

ASIHTTPRequest* req = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"localhost"]] autorelease];
[req setCompletionBlock:^{  
   NSLog(@"It works! Response was %@",[req responseString]);
 }];
[req startAsynchronous];

它使异步响应成为一个快照,并允许您像老板一样使用闭包。

我已经尝试处理内置的NSURLRequest方法有一段时间了,我非常喜欢在不创建单独的委托和处理方法的情况下发出异步请求的简单性。它还支持发布数据和文件,以及我尚未使用的其他一些技巧。