通过POST用户名和密码在UIWebView中加载URL?

时间:2013-02-20 13:20:22

标签: ios uiwebview http-post nsmutableurlrequest

我正在尝试通过自动登录该网站在UIWebView中加载网站。我正在发布用户名和密码。它加载网站但未登录。登录无效。任何想法?

NSURL *url = [NSURL URLWithString:@"http://www.abc.com"];

        NSString *post = [NSString stringWithFormat:@"login_name=%@&login_password=%@&submit=Login", @"abc", @"abc"];
        NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
        NSLog(@"POST Length = %@",postLength);
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];
        [request setTimeoutInterval:5.0];
         [webView loadRequest:request];

2 个答案:

答案 0 :(得分:1)

因为你错过application/x-www-form-urlencodedcharset=utf-8之间的分号会失败吗?

尝试application/x-www-form-urlencoded;charset=UTF-8,看看是否有帮助。

答案 1 :(得分:-1)

我刚用我的代码构建了一个示例应用程序来加载webview。我在表单提交中调用特定页面,它可以登录Web服务。我在这里发布代码:

NSString *username = @"abc";
NSString *password = @"abc";
NSString *postString = [NSString stringWithFormat:@"username=%@&password=%@",username, password];
NSLog(@"%@", postString);
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://www.someurl.com/loginscript"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
[webView loadRequest:request];

也许这段代码可以帮到你。