【问题标题】:load url in UIWebView by POSTing username and password?通过发布用户名和密码在 UIWebView 中加载 url?
【发布时间】:2013-02-20 13:20:21
【问题描述】:

我正在尝试通过自动登录到该网站来加载 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];

【问题讨论】:

    标签: ios uiwebview http-post nsmutableurlrequest


    【解决方案1】:

    是否会因为您在 application/x-www-form-urlencodedcharset=utf-8 之间缺少分号而失败?

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

    【讨论】:

    • 您确定该站点使用 UTF-8 吗?您是否尝试过切换到NSASCIIStringEncoding 并完全删除;charset=UTF-8?您可能希望使用像 Charles 这样的代理来捕获正确的请求格式和标头。
    • 请检查一下。 (Request-Line) POST /login.cgi HTTP/1.1 Host xyz:abc Accept text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 Accept-语言 en-us,en;q=0.5 Accept-Encoding gzip, deflate Connection keep-alive Referer xyz:abc Cookie testing=1 Content-Type application/x-www-form-urlencoded Content-Length 29
    【解决方案2】:

    我刚刚使用我的代码构建了一个示例应用程序来加载 web 视图。我在表单提交中调用了一个特定页面,它可以登录到 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];
    

    也许这段代码会对你有所帮助。

    【讨论】:

    • 它不会有任何区别。只需检查一下。
    • 好的...对不起。我一直在使用帖子,它们工作得很好。我将发布我的示例代码。
    • 我已将答案更改为使用登录脚本调用 webView。
    • 好的。您引用的网页上是否有特定的登录表单?如果是这样,您可以通过查看页面来源并检查
      来获取指导页面。如果操作中有一个页面,那么这就是您需要放入 URL 的页面。希望这会有所帮助。
    • 尝试从您的 postString 中取出 SUBMIT。我不知道会发生什么。我的应用程序以这种方式登录就好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 2013-09-27
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    相关资源
    最近更新 更多