2010-05-03 116 views
1
NSData *data = [[NSData alloc] initWithContentsOfURL:url]; 

Url是一個NSURL,它工作正常。不過,我想在登錄後獲取HTML(數據)。從需要登錄的網站獲取HTML源代碼(iphone)

因此,該網站有一種標準方式,使用2個文本框和表單上的提交操作登錄。

那麼如何登錄然後獲取HTMl源代碼以便我可以解析它。我需要使用非NSData以外的東西嗎?

+0

可能這回答你的問題:http://stackoverflow.com/questions/1005521/iphone-nsdata-nsurl-with-cookie – 2010-05-03 14:13:22

回答

1

我想你想通過POST提交NSURLConnection。你將不得不調整此相匹配的形式,但它應該是類似

NSString *reqURL = [NSString stringWithFormat:@"%@/login",SERVER_URL]; 

    NSMutableURLRequest *req = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:reqURL]]; 
    [req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; 


    NSData *myRequestData = [NSData dataWithBytes:[@"username=whatever&password=whatever" UTF8String] length: [@"username=whatever&password=whatever" length]]; 
    [req setHTTPMethod: @"POST"]; 
    [req setHTTPBody: myRequestData]; 
    NSData *returnData = [NSURLConnection sendSynchronousRequest:req returningResponse: nil error: nil]; 
    NSString *html = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];