Question

J'ai ce formulaire html pour passer mes données de l'iPhone au serveur web .. mais j'ai stucked comment construire ce formulaire / données dans une demande mutable. Pouvez-vous Pls. me conseiller.

formulaire 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>

Je ne sais pas comment assigner dans l'URL demander la « valeur » à la clé spécifique (ex action., Acctid, montant, nom) ???

Ceci est mon code:

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];
Était-ce utile?

La solution

semble correcte, même si vous êtes absent certains signes égal dans votre chaîne de format, et vous avez besoin d'envelopper vos arguments de chaîne en @"":

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

Pour une solution plus extensible, vous pouvez stocker vos paires clé / valeur dans un dictionnaire faire quelque chose comme ceci:

// 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:@"&"]];

(Gardez à l'esprit que vous devrez peut encode les clés et valeurs.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top