2010-01-15 52 views
20

我在將POST數據發送到使用NSURLConnection的PHP腳本時遇到了一些問題。這是我的代碼:使用NSURLConnection發送POST的iPhone

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」。

在某處可能有些蹩腳的錯誤,但我似乎無法找到它?有任何想法嗎?

回答

39

你的數據是錯誤的。如果您預計數據到PHP的$ _POST陣列中找到,它應該是這樣的:

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

如果你想發送的XML數據,您需要設置不同的HTTP內容類型。例如。如果您沒有設置HTTP內容類型,默認類型

application/x-www-form-urlencoded 

將用於您可以設置

application/xml; charset=utf-8 

。這種類型期望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標頭是不是應用程序/ x-WWW - 形式進行了urlencoded。如果它是application/x-www-form-urlencoded,那麼PHP本身會讀取所有後期數據,對其進行解碼(將其分解爲鍵/值對),最後將其添加到$ _POST數組中。

+1

啊是啊......歡呼聲。但是responseData輸出就像「<48656c6c 6f326f72 6c64>」,不要用%@打印NSData嗎? –

+0

謝謝[請求setValue:@「xxx」forHTTPHeaderField:@「Content-Type」]; – Nils

+0

嗨,我使用「text/xml; charset = UTF-8」與HTTP內容類型,發送請求是好的,但我使用「應用程序/ xml;字符集= UTF-8」,並一起去HTTP內容類型是問題,數據將返回:「服務器無法處理請求,因爲媒體類型不受支持」。那麼發生了什麼? – AmyNguyen

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

8

啊是啊...歡呼。但是responseData輸出就像是「< 48656c6c 6f326f72 6c64>」,不要用%@打印NSData嗎? - per_pilot 1月15日在'10 13:57

那是因爲你展示了「字節」的價值觀,你應該把它傳遞給NSString的看到真實的消息

NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding]; 
NSLog(@"responseData: %@", string); 
7
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]; 
+0

標準格式:... stringWithFormat:@「usertype =%@&loginname =%@&password =%@」 ;) – RTOSkit

2

如果您使用NSURLSession然後在iOS9設置

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

在db(MySql5)中設置utf-8_generic。