2010-03-30 4 views
16

Sono abbastanza nuovo rispetto all'obiettivo-c e sto cercando di passare un numero di coppie chiave-valore a uno script PHP utilizzando POST. Sto usando il seguente codice ma i dati non sembrano essere pubblicati. Ho provato a inviare materiale usando NSData, ma nessuno dei due sembra funzionare.Utilizzo di NSURLRequest per passare le coppie valore-chiave allo script PHP con POST

NSDictionary* data = [NSDictionary dictionaryWithObjectsAndKeys: 
    @"bob", @"sender", 
    @"aaron", @"rcpt", 
    @"hi there", @"message", 
    nil]; 

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

[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:[NSData dataWithBytes:data length:[data count]]]; 

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

Sta diventando inviato a questo semplice script per eseguire un inserto db:

<?php $sender = $_POST['sender']; 
     $rcpt = $_POST['rcpt']; 
     $message = $_POST['message']; 

     //script variables 
     include ("vars.php"); 

     $con = mysql_connect($host, $user, $pass); 
     if (!$con) 
     { 
     die('Could not connect: ' . mysql_error()); 
     } 

     mysql_select_db("mydb", $con); 

     mysql_query("INSERT INTO php_test (SENDER, RCPT, MESSAGE) 
     VALUES ($sender, $rcpt, $message)"); 

     echo "complete" 
?> 

Tutte le idee?

+1

Grazie a pinkgothic, ora sono quote-racchiude la mia dichiarazione di inserimento, tuttavia è solo l'aggiunta di valori vuoti al DB . Immagino che questo significhi che i valori non vengono ancora pubblicati correttamente? –

risposta

36

Grazie per i suggerimenti a tutti. Alla fine sono riuscito a risolvere il problema utilizzando materiale dato here.

Codice:

NSString *myRequestString = @"sender=my%20sender&rcpt=my%20rcpt&message=hello"; 
NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ]; 
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString: @"http://people.bath.ac.uk/trs22/insert.php" ] ]; 
[ request setHTTPMethod: @"POST" ]; 
[ request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; 
[ request setHTTPBody: myRequestData ]; 
NSURLResponse *response; 
NSError *err; 
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err]; 
NSString *content = [NSString stringWithUTF8String:[returnData bytes]]; 
NSLog(@"responseData: %@", content); 
0

Modifica: è stato risolto in OP.


questo potrebbe non essere il vostro unico problema (non so il mio modo per aggirare Objective-C), ma qui va:

mysql_query("INSERT INTO php_test (SENDER, RCPT, MESSAGE) 
VALUES ($sender, $rcpt, $message)"); 

Non stai quote-allegando le corde - MySQL è destinato ad avere un sibilo su quello.

mysql_query("INSERT INTO php_test (SENDER, RCPT, MESSAGE) 
VALUES ('$sender', '$rcpt', '$message')"); 

Oltre a ciò, in generale, anche se lo script non è raggiungibile dall'esterno, non si dovrebbe fiducia input dell'utente e usare sia mysql_real_escape_string() per sfuggire i valori prima di inserirle nella istruzione SQL per evitare SQL injection oppure utilizzare prepared statements (preferito), altrimenti le virgolette singole nei dati legittimi interromperanno la sintassi dell'istruzione SQL.

esempio Interamente sgraziata di riferimento:

mysql_query("INSERT INTO php_test (SENDER, RCPT, MESSAGE) 
VALUES ('" . mysql_real_escape_string($sender) ."'," 
." '" . mysql_real_escape_string($rcpt) ."'," 
." '" . mysql_real_escape_string($message) ."')"); 
2

Questa linea [request setHTTPBody:[NSData dataWithBytes:data length:[data count]]]; guarda modo sbagliato per me.

Penso che si desidera: [request setAllHTTPHeaderFields:data];

In secondo luogo, si trova il framework Cocoa maiuscola la prima lettera i nomi dei campi, prima di inviarli (fastidiosamente). Potrebbe essere necessario apportare alcune modifiche per far fronte a questo.

+0

Non abbiate paura - ora sto ottenendo: 400 Richiesta

400 Bad Request

Il suo cliente ha emesso una richiesta non valida o illegale. indietro da sendSynchronousRequest: metodo. Ci sono altri campi di intestazione che devo inviare per conformarmi con HTTP? –

2

Se si desidera eseguire molti post di registrazione, si consiglia di ignorare NSURLRequest e utilizzare invece ASIHTTPRequest. IMHO, è ben documentato e offre un modo semplice per interagire con i servizi web.

+0

grazie, ma non sto cercando di usarlo più di questo una volta in tutto il progetto davvero. Anche se mi piace l'aspetto di quanto sia facile pubblicare cose. –

4

Questo è sbagliato:

[NSData dataWithBytes:[post UTF8String] length:[post length]] 

La lunghezza dovrebbe essere espressa in byte non nel conteggio dei caratteri UTF8. Invece di questa linea si dovrebbe usare:

NSData *data = [post dataUsingEncoding: NSUTF8StringEncoding]; 
+0

Provato quasi tutto, il tutto era in questa stringa. Grazie! – blackhawk4152

1

Questo sta lavorando su IOS 5.o per distacco Forma e ottenere i dati:

self.requestFor = serviceNameT; 

responseData = [[NSMutableData data] retain]; 

SharedResponsedObject* sharedResponsedObject = [SharedResponsedObject returnSharedInstance]; 
LoginInfo* loginInfo = (LoginInfo*)sharedResponsedObject.loginInfo; 

NSLog(@"DEVICE_TOKEN: %@, loginInfo.sessionId: %@, itemIdT: %@", DEVICE_TOKEN, loginInfo.sessionId, itemIdT); 

NSString* requestStr = [NSString stringWithFormat:@"Token=%@&SessionId=%@&ItemId=%@", DEVICE_TOKEN, loginInfo.sessionId, itemIdT]; 


NSData *myRequestData = [ NSData dataWithBytes: [ requestStr UTF8String ] length: [ requestStr length ] ]; 

NSMutableURLRequest *request = [[ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:@"http://menca.com:1500/DownloadContent.aspx"]]; 

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


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

Grazie & saluti, Arun Dhwaj

Problemi correlati