简单的POST消息到服务器

时间:2013-05-28 06:38:58

标签: ios objective-c

我想向我的php脚本发送一条简单的消息(NSString)。我正在尝试发出POST请求。我无法做到这一点,我不确定我做错了什么。有人能告诉我我的错误吗?

谢谢!

PHP代码

 <?php

if($_POST['error'])
{
$date= time();
$error=$_POST['error'];
$message=$date." ".$error;

echo $message;

//Rest of code just writes to a log file
 ?>

---------------------

NSString *post =[[NSString alloc] initWithFormat:@"error=%@",serverError];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding                            allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://mysite.com/error.php"]];

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(@"responseData is %@", responseData);

1 个答案:

答案 0 :(得分:2)

试试这个

NSString *post = [NSString stringWithFormat:@"error=%@", serverError];

而不是

NSString *post = [[NSString alloc] initWithFormat:@"error=%@", serverError];