问题描述
我正在处理POST请求,并且一直在使用此 answer . NSUrlRequest(和连接)文档很多,但是我很难弄清为什么该请求不起作用.
I am working on a POST request and have been using this answer. There is a lot of documentation NSUrlRequest (and connection) but I am having trouble figuring out why the request won't work.
-
我已使用此代码使用HTTP Dev Client成功执行了POST
I have performed a successful POST using an HTTP Dev Client using this code
entry.0.single=name&entry.1.single=location&entry.4.single=phoneNumber&entry.2.single=order????&pageNumber=0&backupCache=
这4个变量(名称,位置,电话号码,顺序)都链接到应用程序中的textFields.
The 4 variables (name, location, phoneNumber, order) are all linked to textFields in the app.
- (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和开发人员文档.任何想法将不胜感激.谢谢
I think I might be missing something subtle but I have been pouring through stackoverflow and developer documentation. Any thoughts would be much appreciated. Thanks
推荐答案
您将需要实现NSURLConnectionDelegate
协议,将[nsUrlConnection setDelegate:self];
放入代码中,并添加-connectionDidFinishLoading:
,-connection:didReceiveData:
和-connectionDidFailWithError:
方法到您的代码中并捕获响应数据:
You would need to implement the NSURLConnectionDelegate
protocol, put [nsUrlConnection setDelegate:self];
into your code and add the -connectionDidFinishLoading:
, -connection:didReceiveData:
and -connectionDidFailWithError:
methods into your code and capture the response data:
.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 App通过HTTP POST到Google Form的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!