Ios NSURLConnection没有响应
我有以下代码,只需加载包含post数据的URL,然后从服务器获取HTML响应:Ios NSURLConnection没有响应,ios,objective-c,cocoa-touch,cocoa,nsurlconnection,Ios,Objective C,Cocoa Touch,Cocoa,Nsurlconnection,我有以下代码,只需加载包含post数据的URL,然后从服务器获取HTML响应: // Send log in request to server NSString *post = [NSString stringWithFormat:@"username=%@&password=%@", text_field_menu_username.text, text_field_menu_password.text]; NSData *postData = [post dataUsingEnco
// Send log in request to server
NSString *post = [NSString stringWithFormat:@"username=%@&password=%@", text_field_menu_username.text, text_field_menu_password.text];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request;
[request setURL:[NSURL URLWithString:@"http://example.com/test.php"]]; // Example Only
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
// Handle response
NSString *response_string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Data 1: %@", response);
NSLog(@"Data 2: %@", data);
NSLog(@"Data 3: %@", error);
NSLog(@"Data 4: %@", response_string);
}];
以下是每个NSLog
的输出:
Data 1: (null)
Data 2: (null)
Data 3: (null)
Data 4:
知道我做错了什么吗?在设置参数之前,您还没有初始化
请求对象。应该是:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
所有变量均为零?我用每个NSLog
的%d
的确切输出更新了问题,该变量是NSData的长度使用的错误转换说明符;这是错误的标志,在某些架构上,是错误的大小。你应该得到一个关于这个的警告;如果您没有,您应该打开该警告(“Typecheck calls toprintf
/scanf
”)。很有意思,谢谢提醒!完美的对于将来研究这个问题的人来说,response\u string
变量就是包含正确响应的变量。