【问题标题】:NSMutableURLRequest proper postingNSMutableURLRequest 正确发布
【发布时间】:2011-04-09 20:39:16
【问题描述】:

所以我正在尝试使用 NSMutableURLRequest 登录我的网站,它通过帖子提供凭据。作为菜鸟,我对这种方法的功能有一些疑问,以确保我理解它。

NSString *post = [NSString stringWithFormat:@"username=%@&password=%@&TARGET=%@",LoginId,LoginPwd,target];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setHTTPShouldHandleCookies:YES];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://somelogin.mycomp.verify.fcc"]]];
//[request setURL:url];
[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];

现在这将通过委托方法自动处理任何重定向,对吗?它还会一路收集任何cookies吗?另外,我应该改用异步请求吗?谢谢!

更新: 所以我推断出一些 cookie 被请求和后续重定向忽略了。有谁知道为什么会发生这种情况?

【问题讨论】:

    标签: iphone objective-c ipad ios4


    【解决方案1】:

    同步登录的时候可以做这样的事情……代码并不完美,但大体思路是这样的。

    在此处查找文档

    https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/AuthenticationChallenges.html#//apple_ref/doc/uid/TP40009507-SW1

    // credentials set here
    NSURLCredential *creds = [NSURLCredential credentialWithUser:LoginId password:LoginPwd
                                               persistence:NSURLCredentialPersistenceForSession];
    
    NSURLProtectionSpace *protectionedSpace = [[NSURLProtectionSpace alloc]
      initWithHost:@"mycomp.verify.fcc"
      port:8443
      protocol:@"https"
      realm:nil
      authenticationMethod:nil];
    
    
    [[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:creds
                                                forProtectionSpace:protectionedSpace];
    
    // removed credentials from line...
    NSString *post = [NSString stringWithFormat:@"TARGET=%@",target];
    

    这是一个异步操作的教程

    http://iosdevelopertips.com/networking/handling-url-authentication-challenges-accessing-password-protected-servers.html

    【讨论】:

    • 有趣,是否可以更改 cookie 存储(安全)策略?我觉得因为它是在不同的域上进行身份验证,所以后续的重定向不会收集 cookie。
    • 我已经实现了一个解决方案,我在凭证存储中加载特定域的所有凭证......所以当 URL 请求凭证时,他们可以从商店中检索它们
    • 对,我没有选择使用基于质询的身份验证。我必须通过所有的箍来收集饼干。如果我有那个选项会容易得多...
    • 想通了,感谢您的回复!我需要用更好的重定向来修改我的初始帖子。现在它完美地工作了。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    相关资源
    最近更新 更多