【问题标题】:Sending POST data with NSURLConnection or ASIHTTPRequest使用 NSURLConnection 或 ASIHTTPRequest 发送 POST 数据
【发布时间】: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


【解决方案1】:

我认为你必须在发布数据之前设置一些http头,然后只有php才能识别使用post方法请求的页面

试试这条线

[请求setHTTPMethod:@"POST"];

【讨论】:

  • ASIHTTP 设置为自动发布,我尝试了一个 NSURLConnection 方法设置为 POST 并得到了与上述问题的编辑相同的结果。我认为服务器端有问题?
【解决方案2】:

试试看。

    NSURL *url = [[NSURL alloc] initWithString:@"http://server.com/s.php"];
   ASIHTTPRequest *Asi_request = [ASIHTTPRequest requestWithURL:url];
    [request setPostValue:@"Ben" forKey:@"fname"];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestFinished:)];
    [request startAsynchronous];
[request setHTTPMethod: @"POST"];

//如果这不起作用那么你应该在appledelegate文件中生成队列见:link

希望对您有所帮助。

【讨论】:

  • ASIHTTPRequest 不响应“setHTTPMethod”,我很确定它会自动将其设置为 POST
  • [Asi_request setRequestMethod:@"POST"];这里 Asi_request 是 ASIHTTPRequest 的对象。我正在使用这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-23
  • 1970-01-01
相关资源
最近更新 更多