1

iPhoneからWebサーバーにデータを渡すためのこのhtmlフォームがあります..しかし、このフォーム/データを変更可能なリクエストに組み込む方法に行き詰まりました。よろしくお願いします。アドバイスを下さい。

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

1 に答える 1

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 エンコードする必要がある場合があることに注意してください。)

于 2010-11-25T15:12:24.027 に答える