开发者

Getting HTML source(NSData) from website that needs logging in (iphone)

NSData *data = [[NSData alloc] initWithContentsOfURL:url];

Url is an NSURL and it works fine. However I'd like to get the HTML (data) after I've logged in.

So the website has a standard way of logging in with 2 textboxes and a submit action on the form.

So how can I log in then get the HTMl source so I can parse it. Do 开发者_如何学JAVAi have to use something other than NSData?


I think you want to submit the form via a POST with NSURLConnection. You will have to adjust this to match the form, but it should be something like

    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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜