iPhone使用NSURLConnection发送POST请求

21

我使用NSURLConnection发送POST数据到PHP脚本时遇到了一些问题。这是我的代码:

    const char *bytes = [[NSString stringWithFormat:@"<?xml version=\"1.0\"?>\n<mydata>%@</mydata>", data] UTF8String];

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

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];

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

我的 script.php 很简单,就是这样:

<?php
    echo $_POST['mydata'];
?>

这个方法以前对我有用过,但现在当我使用NSLog(@"responseData: %@", responseData);时,输出只是"<>"而不是"theData"。

可能是某个愚蠢的错误导致的,但我找不到原因,有什么想法吗?

5个回答

39

你的数据是错误的。如果你期望在 PHP 的 $_POST 数组中找到这个数据,它应该是这个样子:

const char *bytes = "mydata=Hello%20World";

如果你想发送XML数据,你需要设置不同的HTTP内容类型。例如,你可能会设置

application/xml; charset=utf-8
如果没有设置HTTP内容类型,则使用默认类型。
application/x-www-form-urlencoded

将被使用。而且这种类型希望POST数据的格式与GET请求中的格式相同。

然而,如果您设置了不同的HTTP内容类型,例如application/xml,那么在PHP中,这些数据不会添加到$_POST数组中。您将需要从输入流中读取原始数据。

尝试一下:

NSString * str = [NSString stringWithFormat:@"<?xml version=\"1.0\"?>\n<mydata>%@</mydata>", data];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[str dataUsingEncoding:NSUTF8StringEncoding]];

在服务器上尝试以下 PHP 代码:

$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
    $http_raw_post_data .= fread($handle, 8192);
}
fclose($handle);
请注意,这仅在您的POST请求的HTTP头部不是application/x-www-form-urlencoded时才起作用。如果它是application/x-www-form-urlencoded,那么PHP本身将读取所有的POST数据,并将其解码(分成键/值对),最后将其添加到$_POST数组中。

1
啊,是的...谢谢。但是responseData输出的是类似于“<48656c6c 6f326f72 6c64>”这样的内容,你难道不是用%@打印NSData吗? - per_pilot
感谢您使用 [request setValue:@"xxx" forHTTPHeaderField:@"Content-Type"]; - Manifestor
嗨,我使用"text/xml; charset=utf-8"作为HTTP Content-Type,在发送请求时没问题,但是如果我同时使用"application/xml; charset=utf-8"和HTTP Content-Type一起发送请求的话就会出现问题,返回的数据是:"The server cannot service the request because the media type is unsupported"。所以这是怎么回事呢? - AmyNguyen

7
啊,对了,干杯。但是responseData的输出看起来像“<48656c6c 6f326f72 6c64>”,你不应该用%@打印NSData吗? - per_pilot Jan 15 '10 at 13:57
那是因为你正在显示“bytes”值,你应该将其传递给NSString以查看实际消息。
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(@"responseData: %@", string);

6
NSString *post =[NSString stringWithFormat:@"usertype(%@),loginname(%@),password(%@)",txtuser.text,txtusername.text,txtpassword.text];
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://www.dacinci.com/app/tes2/login_verify.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

标准格式:...stringWithFormat:@"usertype=%@&loginname=%@&password=%@";) - RTOSkit

2
POST数据和XML数据是不同的。您可以像以前一样发送XML数据,但是PHP代码必须从请求正文中解析XML。PHP的xml_parse (http://php.net/manual/en/function.xml-parse.php) 可以帮助您完成这个任务。
或者,如果你更喜欢发送POST数据,请将请求正文设置为以下内容: const char *bytes = [[NSString stringWithFormat:@"mydata=%@", data] UTF8String];

1
如果您使用NSURLSession,则在iOS 9中设置:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
request.HTTPMethod = @"POST";

在 PHP 中设置。
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) 
  or die("Unable to connect to MySQL");
  echo "Connected to SQL.";

//select a database to work with
$selected = mysql_select_db($db,$dbhandle) 
  or die("Could not select anons db");
  echo "Connected to DB sucess.";

mysql_query("SET NAMES 'utf8'"); 
mysql_query("SET CHARACTER SET 'utf8'");
mysql_query("SET SESSION collation_connection = 'utf8_general_ci'");

在数据库(MySql5)中设置utf-8_generic。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接