2010-01-15 20 views
20

Sto riscontrando qualche problema con l'invio di dati POST a uno script PHP con NSURLConnection. Questo è il mio codice:iPhone invia POST con NSURLConnection

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

E la mia script.php è semplice come questo:

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

Questo hanno lavorato per me in passato, ma per qualche motivo l'uscita che ricevo da NSLog(@"responseData: %@", responseData); ora è solo "<>" anziché "theData".

Probabilmente qualche errore da qualche parte ma non riesco a trovarlo? Qualche idea?

risposta

39

I dati sono sbagliati. Se vi aspettate i dati che si trovano nella matrice $ _POST di PHP, dovrebbe assomigliare a questo:

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

Se si desidera inviare i dati XML, è necessario impostare un diverso tipo HTTP Content. Per esempio. è possibile impostare

application/xml; charset=utf-8 

Se si imposta no Tipo HTTP Content, il tipo predefinito sarà usato

application/x-www-form-urlencoded 

. E questo tipo si aspetta che i dati POST abbiano lo stesso formato che avrebbe in una richiesta GET.

Tuttavia, se si imposta un tipo di contenuto HTTP diverso, ad esempio application/xml, questi dati non vengono aggiunti all'array $ _POST in PHP. Dovrai leggere il raw dal flusso di input.

Prova questo:

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

e sul server di provare quanto segue PHP:

$handle = fopen("php://input", "rb"); 
$http_raw_post_data = ''; 
while (!feof($handle)) { 
    $http_raw_post_data .= fread($handle, 8192); 
} 
fclose($handle); 

prega di notare che questo funziona solo se l'header HTTP del tuo post non è application/x-www -Form-urlencoded. Se è application/x-www-form-urlencoded allora PHP stesso legge tutti i dati del post, lo decodifica (dividendolo in coppie chiave/valore) e infine lo aggiunge all'array $ _POST.

+1

Ah sì ... grazie. Ma l'output responseData è come "<48656c6c 6f326f72 6c64>", non si stampa NSData con% @? –

+0

grazie per [request setValue: @ "xxx" forHTTPHeaderField: @ "Content-Type"]; – Nils

+0

Ciao, io uso "text/xml; charset = utf-8" con HTTP Content-Type, la richiesta di invio è ok ma io uso "application/xml; charset = utf-8" e anche andare insieme HTTP Content-Type è un problema , dati restituiti: "Il server non può servire la richiesta perché il tipo di supporto non è supportato". Quindi cosa succede? – AmyNguyen

2

I dati POST e dati XML non sono gli stessi. Puoi inviare dati XML proprio come hai fatto tu, ma il codice PHP deve analizzare l'XML dal corpo della richiesta. PHP xml_parse (http://php.net/manual/en/function.xml-parse.php) può aiutarti a farlo.

In alternativa, se si preferisce l'invio dei dati POST, impostare il corpo della richiesta in questo modo:

const char *bytes = [[NSString stringWithFormat:@"mydata=%@", data] UTF8String];

8

Ah sì ... applausi. Ma l'output responseData è come "< 48656c6c 6f326f72 6c64>", non si stampa NSData con% @?- per_pilot 15 gen '10 a 13:57

che è perché si sta mostrando i valori "byte" si dia mai per NSString per vedere il vero messaggio

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

formato standard: ... stringWithFormat: @ "usertype =% @ & loginname =% @ & password =% @" ;) – RTOSkit

2

Se uso NSURLSession poi in iOS9 impostato

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

in PHP impostato

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

Nel set db (MySql5) utf-8_generic.