【发布时间】:2011-06-16 05:35:13
【问题描述】:
我尝试使用异步和同步 NSURLConnection 和 ASIHTTPRequest 将 POST 数据发送到 php 文件,但两者都拒绝在 $_POST 中实际回显任何内容。我的 s.php 文件如下所示:
<?php
echo 'Hi There';
echo $_POST['fname'];
foreach ($_POST as $i => $value) {
echo($i);
}
?>
我的 ASIHTT 请求是:
NSURL *url = [[NSURL alloc] initWithString:@"http://server.com/s.php"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"Ben" forKey:@"fname"];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestFinished:)];
[request startAsynchronous];
当它返回 requestFinished 时只打印 Hi There 行。
编辑: 通过使用 ASIFormDataRequest,我很确定请求已经设置为 POST,至少似乎没有办法手动设置它。当我尝试使用 NSURLConnection 时:
NSURL *url = [NSURL URLWithString:@"http://server.com/s.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[[NSString stringWithFormat:@"fname=carl"] dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *stringResponse = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];
NSLog(@"%@",stringResponse);
当我使用 html 表单时,仍然只能收到 Hi There 行,并且还会收到正常回复。
【问题讨论】:
-
在你的代码中加入这一行; [请求 setHTTPMethod:@"POST"];
-
它工作正常user768531。上面的代码没有问题。可能不是代码问题。
-
@impossiblepriya 可能是服务器端的问题?
-
是 "ischool.berkeley.edu/~ariel/server/s2.php" 你的 php 文件在哪里??
-
@impossiblepriya 是的,我贴在上面的 php 文件就在那个地址。
标签: php iphone post nsurlconnection asihttprequest