Domanda

Ho questo modulo HTML per passare i miei dati da iPhone al server web .. Ma ho stucked come costruire questa forma / dati in una richiesta mutevole. Potete trasmetterci. consigliarmi.

form HTML:

<html>
<form method="post" action="https://mysite.com"> 
<input type="hidden" name="action" value="sale"> 
<input type="hidden" name="acctid" value="TEST123"> 
<input type="hidden" name="amount" value="1.00">
<input type="hidden" name="name" value="Joe Customer"> 
<input type="submit"> 
</form>
</html>

Non so come assegnare nell'URL della richiesta il "valore" alla chiave specifica (es. Azioni, acctid, importo, nome) ???

Questo è il mio codice:

NSString *urlString =  @"https://mysite.com";
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];

NSString *post = [[NSString alloc] initWithFormat:@"%@%@&%@%@&%@%@&%@%@", 
   action, sale, 
   acctid, TEST123, 
   amount, 1.00,
                                      name, Joe Customer];  // ????

NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];    
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  

[urlRequest setHTTPMethod:@"POST"];  
[urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];  // multipart/form-data
[urlRequest setHTTPBody:postData];
È stato utile?

Soluzione

guarda intorno a destra, anche se ti manca un po 'di segni di uguaglianza nella vostra stringa di formato, ed è necessario avvolgere le argomenti stringa in @"":

NSString *post = [[NSString alloc] initWithFormat:@"%@=%@&%@=%@&%@=%@&%@=%@", 
    @"action", @"sale", 
    @"acctid", @"TEST123", 
    @"amount", @"1.00",
    @"name", @"Joe Customer"];

Per una soluzione più estensibile è possibile memorizzare le coppie chiave / valore in un dizionario poi fare qualcosa di simile:

// Assuming the key/value pairs are in an NSDictionary called payload

NSMutableString *temp = [NSMutableString stringWithString:@""];
NSEnumerator *keyEnumerator = [payload keyEnumerator];
id key;
while (key = [keyEnumerator nextObject]) {
    [temp appendString:[NSString stringWithFormat:@"%@=%@&", 
        [key description], 
        [[payload objectForKey:key] description]]];
}
NSString *httpBody = [temp stringByTrimmingCharactersInSet:
    [NSCharacterSet characterSetWithCharactersInString:@"&"]];

(Tenete a mente potrebbe essere necessario codifica URL le chiavi ei valori.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top