我是iphone开发的新手。我已经发布了包含用户名和密码的URL。我可以在“connection didReceiveData”方法中打印数据。但是我看到“connection didReceiveData”方法被调用了两次。我不知道我要去哪里。这是我的代码
- (void)viewDidLoad {
[super viewDidLoad];
NSString *post = [NSString stringWithFormat:@"&domain=school.edu&userType=2&referrer=http://apps.school.edu/navigator/index.jsp&username=%@&password=%@",@"xxxxxxx",@"xxxxxx"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://secure.school.edu/login/process.do"]]];
[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];
if(conn)
{
NSLog(@"Connection Successful");
}
else
{
NSLog(@"Connection could not be made");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"the data %@",string);
}
整个HTML页面在控制台中打印了两次,请帮帮我。
最佳答案
您可能会分块接收响应数据,这就是NSURLConnection's documentation指出的原因:
“委托(delegate)人应将所传递的每个数据对象的内容串联起来,以构建用于URL加载的完整数据。”
为此,请使用NSMutableData
实例,并且仅在收到-connectionDidFinishLoading:
消息后才处理完整数据。