我有这个代码用于向PHP页面发送POST请求:
NSString *urlString = @"http://example.php";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *variableToSend = [NSString stringWithFormat:@"test=my real data"];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", [variableToSend length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[variableToSend dataUsingEncoding:NSUTF8StringEncoding]];
// Create url connection and fire request
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSLog(@"Response: %@",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
这很好用。但是,如果我想要更多变量怎么办?使用上面的代码,我可以在PHP中执行此操作:$ _POST ['test']并打印出“我的真实数据”。但是,如果我想要另一个POST参数怎么办?也许像$ _POST [“另一个”]?我将如何做到这一点。
谢谢大家
答案 0 :(得分:2)
如果你需要从整数,浮点数,字符串等发送数据......你可以这样做: 例如,您要发送名称和姓氏
NSString *sendData = @"name=";
sendData = [sendData stringByAppendingString:[NSString stringWithFormat:@"%@", name]];
sendData = [sendData stringByAppendingString:@"&lastname="];
sendData = [sendData stringByAppendingString:[NSString stringWithFormat:@"%@", lastname]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com/userName"]];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
//Here you send your data
[request setHTTPBody:[sendData dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:@"POST"];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
{
NSLog(@"Error");
}
else
{
//The response is in data
}
在php中,我总是返回一个带有json_encode的数组,然后,我使用NSDictionary在ios中读取它
答案 1 :(得分:0)
您感兴趣的是这一行:
NSString *variableToSend = [NSString stringWithFormat:@"test=my real data"];
在这样的HTTP请求中,您将参数与&
分开,如下所示:
NSString *variableToSend = [NSString stringWithFormat:@"field1=value&field2=othervalue"];