Send POSTs to a PHP script on a server

2020-07-26 11:33发布

问题:

I have a PHP script on a server

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

How do I now send a POST request from my iPhone app...

ive tried this sort of thing...

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

Any ideas? Thanks guys

Sam

EDIT:

i think there is something wrong with my request body

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

remember that my php variables are $comment and $email

回答1:

try to add:

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

After:

[request setHTTPBody:requestBody];

In your script

Edit:

Since I don't have a sdk available I can't test it for you but could you try this?:

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 


回答2:

try to use @"comment=%@&email=%@" instead of @"comment:%@&email%@"