我正在处理 POST 请求并且一直在使用这个 answer .有很多文档 NSUrlRequest(和连接),但我无法弄清楚为什么请求不起作用。
我已使用此代码使用 HTTP Dev Client 成功执行了 POST
entry.0.single=name&entry.1.single=location&entry.4.single=phoneNumber&entry.2.single=order????&pageNumber=0&backupCache=
4 个变量(姓名、位置、电话号码、订单)都链接到应用中的文本字段。
- (IBAction)placeOrder:(id)sender { NSURL *nsURL = [[NSURL alloc] initWithString:@"url"]; NSMutableURLRequest *nsMutableURLRequest = [[NSMutableURLRequest alloc] initWithURL:nsURL]; // Set HTTP method to POST [nsMutableURLRequest setHTTPMethod:@"POST"]; // Set up the parameters to send. NSString *paramDataString = [NSString stringWithFormat:@"%@=%@&%@=%@&%@=%@&%@=%@&pageNumber=0&backupCache=",@"entry.0.single", _name, @"entry.1.single", _location, @"entry.4.single", _phoneNumber, @"entry.2.single", _order]; // Encode the parameters to default for NSMutableURLRequest. NSData *paramData = [paramDataString dataUsingEncoding:NSUTF8StringEncoding]; // Set the NSMutableURLRequest body data. [nsMutableURLRequest setHTTPBody: paramData]; // Create NSURLConnection and start the request. NSURLConnection *nsUrlConnection=[[NSURLConnection alloc]initWithRequest:nsMutableURLRequest delegate:self]; [ nsUrlConnection start]; }
我想我可能遗漏了一些微妙的东西,但我一直在仔细阅读 stackoverflow 和开发人员文档。任何想法将不胜感激。谢谢
最佳答案
您需要实现 NSURLConnectionDelegate
协议(protocol),将 [nsUrlConnection setDelegate:self];
放入您的代码中并添加 -connectionDidFinishLoading:
、-connection:didReceiveData:
和 -connectionDidFailWithError:
方法到您的代码中并捕获响应数据:
.h
NSMutableData *responseData;
.m
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"RESPONSE: %@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"CONNECTION ERROR: %@", [error localizedDescription]);
}
关于ios - 从 iOS 应用程序到 Google 表单的 HTTP POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17748132/