1

我正在尝试使用 NSURLConnection 使用我的用户名和密码进行连接和登录。我可以发出发布请求并收到回复,但我无法保持会话。在我提出请求后,我从网站收到这条消息:

该系统需要使用 HTTP cookie 来验证授权信息。我们的系统检测到您的浏览器已禁用 HTTP cookie 或不支持它们。请参阅浏览器中的帮助页面,了解有关如何正确配置浏览器以用于本系统的更多信息。

我建立连接的代码在这里:

NSMutableURLRequest *request = nil;
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://loginsite.com"]];
[[NSHTTPCookieStorage sharedHTTPCookieStorage]setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];

NSString *post = [NSString stringWithFormat:@"username=username&pass=password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
[request setTimeoutInterval: 15];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];

_urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[_urlConnection start];

如果有人可以帮助我,我会很高兴。

4

1 回答 1

0

他们可能会检查您发送的用户代理标头。在这种情况下没有....

1)添加兼容的标头

    NSString *myAgent = @"SOME AGENT StRING";
    [request setValue:myAgent forHTTPHeaderField:@"User-Agent"];

例如来自 AFNetworking 的代理字符串

    #if __IPHONE_OS_VERSION_MIN_REQUIRED
        // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
        [self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey) ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0f)]];
    #elif __MAC_OS_X_VERSION_MIN_REQUIRED
        [self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]];
    #endif

2)获取响应cookie并在未来对主会话的请求中使用它们

nextR.requestCookies = rLogin.responseCookies.mutableCopy;
于 2012-12-05T21:29:54.793 回答