我正在尝试使用以下代码对服务器执行简单的POST请求:
NSString *post = [[NSString alloc] initWithFormat:@"email=%@&password=%@", self.email.text, ..]; // .. simplified keychainItem
NSData *postEncoded = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:@"%d", [postEncoded length]];
NSURL *url = [NSURL URLWithString:@"http://eng.studev.groept.be/web2.0/a11_web02/testApp.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postEncoded];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
在服务器上进行调试时,实际上会产生GET请求。这就解释了为什么我在尝试读取$ _POST []变量时遇到PHP错误。一句话:为什么不是setHTTPMethod:被接受?
(额外信息:当在服务器上用PHP编码时,使用POST工作正常)