2012-12-05 43 views
1

我想通過使用NSURLConnection連接並使用我的用戶名和密碼登錄。我可以提出發帖請求,也可以收到回覆,但我無法保持會話。收到我的請求後,我收到以下消息:無法維護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]; 

我會很高興,如果有人能幫助我。

回答

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)採取的應對餅乾,並利用它們在未來的請求主會話

nextR.requestCookies = rLogin.responseCookies.mutableCopy;