如何在Cocoa中发出POST请求?

时间:2013-10-08 08:52:11

标签: cocoa

这是我的代码,我的代码正在运行,但我的问题是当我尝试在NSString *postString = @"username=example&firstlastname=example";上传递变量而不是名称时,它说示例我想=一个TextField值,那么我该怎么做呢?我试过发布字符串附加字符串,但它没有用。请帮忙

NSURL *aUrl= [NSURL URLWithString:@"http://xxxx/iqueueinsertinjoinq.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"username=example&firstlastname=example";

[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

//NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request delegate:self];
 [[NSURLConnection alloc] initWithRequest:request delegate:self ];}

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,你会想要的是: 变化:

NSString *postString = @"username=example&firstlastname=example";

要:

NSString *username = @"foo";
NSString spokenname = @"bar";
NSString *postString = [NSString stringWithFormat:@"username=%@&firstlastname=%@", username, spokenname];

NSString的stringWithFormat:允许格式字符串中的变量替换。在我的示例中,“username”是包含用户名的NSString变量,“spokenname”是firstnamelastname字符串。