2010-11-25 89 views
1

我有這個HTML表單將我的數據從iPhone傳遞到網絡服務器..但我已經stucked如何建立這種形式/數據到一個可變的請求。你可以請。告訴我。URL請求表格

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> 

我不知道如何在URL請求分配 「值」 的特定鍵(如動作,acctid,數量,名稱。)???

這是我的代碼:

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

回答

3

看起來正確的,但是你錯過了一些等於在你的格式字符串跡象,你需要用你的字符串參數起來@""

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

對於更加可擴展的解決方案,您可以將您的鍵/值對存儲在字典中,然後執行如下操作:

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

(請記住,您可能需要對鍵和值進行URL編碼。)

+0

明白了..謝謝Simon .. – 2010-11-27 16:55:10