我有这个html表单将我的数据从iphone传递到Web服务器.. 但我已经陷入困境,如何将这个表单/数据构建成一个可变的请求。你能来吗?建议我。
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请求中为特定键分配“值”(例如action,acctid,amount,name)???
这是我的代码:
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];
答案 0 :(得分: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编码。)