【发布时间】:2014-02-23 16:38:40
【问题描述】:
我四处搜索,找不到正确的答案,但我有这段代码将数据发布到我的网络服务器,我正在尝试获取 HTTP 响应,但响应不断返回 (null) .我可以确认连接成功,因为 if 语句(见下文)执行了相应的代码。
这是我的代码:
-(void)submitAction{
NSString *post = [NSString stringWithFormat:@"&var1=%@&var2=%@&var3=%@&var4=%@",
_var1, _var2, _var3, _var4];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://my-web-server.com/path-to-web-service/"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
NSURLResponse *response;
NSLog(@"%@", response); // Always returns null :(
if(conn){
NSLog(@"Connection Successful."); // Connection is successful in my tests.
}else{
NSLog(@"Connection could not be made");
}
}
这是在我的 .h 文件中实现的 NSURLConnectionDelegate 委托:
@interface AddTaskViewController : UIViewController <UITextFieldDelegate, UIPickerViewDelegate, NSURLConnectionDelegate>
谁能看到我在这里做错了什么?服务器应该返回一个 JSON 字符串(当我通过浏览器测试 Web 服务时它会返回)但 NSURLResponse 始终为空。
谢谢,
彼得
【问题讨论】:
-
你必须实现NSURLConnectionDelegate协议。阅读委托here。
-
我已经在我的 .h 文件中实现了这个委托。稍等,我会更新我的代码。
-
你不能在 .h 文件中实现任何东西。您在 .m 文件中实现委托。
-
再次阅读this,了解什么是委托以及如何使用它。
-
顺便说一句,您的帖子正文开头有额外的
&。其次,您应该在各个值上使用CFURLCreateStringByAddingPercentEscapes,而不是使用dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES,如this answer 末尾所示。
标签: ios objective-c nsurlconnection nsurl nsurlrequest