开发者

URL Request Form

开发者 https://www.devze.com 2023-01-26 18:16 出处:网络
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.

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 *p开发者_开发知识库ost = [[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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消