将POST发送到服务器上的PHP脚本

时间:2010-04-14 10:26:04

标签: php iphone post nsurlconnection

我在服务器上有一个PHP脚本

<?php

// retrieve POST vars
$comment = $_POST['comment'];
$email = $_POST['email'];

// remove trailing whitespace etc
$comment = trim($comment);
$email = trim($email);

// format date accoring to http://www.w3schools.com/php/func_date_date.asp
$date_time = date("Y-m-d-H-i-s"); // i.e. 2010-04-15-09-45-23

// prepare message
$to = "(removed my email addy)"; //who to send the mail to
$subject = "Feedback from iPhone app"; //what to put in the subject line
$message = "Name/Email: $email \r\n Comment: $comment";
  mail($to, $subject,$message) or "bad";

echo "ok";
?>

我现在如何从我的iPhone应用程序发送POST请求...

我试过这种事......

NSURL *url = [NSURL URLWithString:@"mysite.com/script.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];

NSString *message = boxForSuggestion.text;
NSString *userEmailString = usersEmail.text;


NSString *requestBodyString = [NSString stringWithFormat:@"comment:%@&email%@", message , userEmailString];

NSData *requestBody = [requestBodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"
[request setHTTPBody:requestBody];
 [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; // added from first suggestion 
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];

NSLog(@"%@", responseString);

有什么想法吗?谢谢你们

萨姆

编辑:

我认为我的请求正文有问题

NSData *requestBody = [requestBodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"
[request setHTTPBody:requestBody];

记住我的php变量是$ comment和$ email

2 个答案:

答案 0 :(得分:3)

尝试添加:

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

后:

[request setHTTPBody:requestBody];

在你的剧本中

编辑:

由于我没有可用的sdk,我无法为你测试,但你可以尝试一下吗?:

NSURL *url = [NSURL URLWithString:@"mysite.com/script.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

 NSString *requestBodyString = [NSString stringWithFormat:@"comment=%@&email=%@", message , userEmailString];
 NSData *requestBody = [NSData dataWithBytes:[requestBodyString UTF8String]length:[requestBodyString length]];

 [request setHTTPMethod:@"POST"
 [request setHTTPBody:requestBody];
 [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; // added from first suggestion 

答案 1 :(得分:1)

尝试使用 @"comment=%@&email=%@"代替@"comment:%@&email%@"

相关问题