简体   繁体   English

使用NSURLConnection或ASIHTTPRequest发送POST数据

[英]Sending POST data with NSURLConnection or ASIHTTPRequest

I have tried sending POST data to a php file with asynch and synch NSURLConnection and ASIHTTPRequest but both refuse to actually echo anything in $_POST. 我曾尝试通过异步和同步NSURLConnection和ASIHTTPRequest将POST数据发送到php文件,但两者都拒绝实际回显$ _POST中的任何内容。 My s.php file looks like so: 我的s.php文件如下所示:

<?php
echo 'Hi There';
echo $_POST['fname'];
foreach ($_POST as $i => $value) {
     echo($i);
}
?>

My ASIHTTRequest is: 我的ASIHTTRequest是:

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];

Which only prints the Hi There line when it comes back to requestFinished. 仅在返回到requestFinished时才打印Hi There行。

Edit: By using ASIFormDataRequest, I am pretty sure request is set to POST already, at least there doesn't seem to be a way to set it manually. 编辑:通过使用ASIFormDataRequest,我很确定请求已设置为POST,至少似乎没有一种手动设置它的方法。 When I tried NSURLConnection I used: 当我尝试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);

And still only getting the Hi There line, and also getting normal replies when I use an html form. 而且仍然只获得Hi There行,并且当我使用html表单时也得到正常答复。

I think you have to set some http headers also before posting data, then only php can recognize that the page requested using post method 我认为您还必须在发布数据之前设置一些http标头,然后只有php才能识别使用post方法请求的页面

try with this line 试试这条线

[request setHTTPMethod: @"POST"]; [request setHTTPMethod:@“ POST”];

Try it. 试试吧。

    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"];

//if this will not work then you should generate queue in appledelegate file see: link //如果这不起作用,则应在appledelegate文件中生成队列,请参阅: 链接

may this help you. 可以帮助您。

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

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