문제

I have this html form to pass my data from iphone to web server.. but I've got stucked how to build this form/data into a mutable request. Can you pls. advise me.

Html form:

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

I don't know how to assign in the url request the "value" to the specific key (ex. action, acctid, amount, name) ???

This is my 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];
도움이 되었습니까?

해결책

Looks about right, although you're missing some equals signs in your format string, and you need to wrap your string arguments up in @"":

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

For a more extendable solution you could store your key/value pairs in a dictionary then do something like this:

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

(Bear in mind you may need to URL-encode the keys and values.)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top