我正在尝试使用NSURLConnection连接并使用我的用户名和密码登录。我可以提出发布请求并收到回复,但我无法保持会话。在我提出请求后,我从网站收到此消息:
此系统需要使用HTTP cookie来验证授权信息。 我们的系统检测到您的浏览器已禁用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];
如果有人可以帮助我,我会很高兴。
答案 0 :(得分:0)
他们可能会检查您发送的用户代理标头。在这种情况下没有......
1)添加兼容的标题
NSString *myAgent = @"SOME AGENT StRING";
[request setValue:myAgent forHTTPHeaderField:@"User-Agent"];
e.g。来自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;