2012-02-12 74 views
11

我想在我的iPhone應用程序中創建一個登錄。如何使用NSURLRequest設置Cookie?

NSURL *urlNew = [NSURL URLWithString:urlstring]; 
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:urlNew]; 
NSString *msgLength = [NSString stringWithFormat:@"%d", [parameterString length]]; 
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"]; 
[theRequest setHTTPMethod:@"POST"]; 
[theRequest setValue:length forHTTPHeaderField:@"Content-Length"]; 
[theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[theRequest setHTTPBody: httpbody]; 

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; 

[connection start]; 

這就是我如何上傳我的數據到服務器的方式,它的工作原理 - 我得到迴應。問題是,響應是登錄端的代碼,而不是「保存」區域的代碼。我想我必須創建cookie,以便網站知道我已登錄。

我搜索了互聯網,但沒有發現任何有用的信息。那麼我在登錄時如何創建一個cookie?當我要去「保存」區域的另一個鏈接時,我是否每次都必須發佈此cookie?

希望你能擺脫我的問題。

格爾茨

+0

你應該改變你的問題「如何獲得一個Cookie用NSURLRequest?「因爲你說你想讓現有的cookie不會創建一個新的。 – Maziyar 2014-05-27 06:40:21

回答

27

試試這個

[theRequest setValue:@"myCookie" forHTTPHeaderField:@"Cookie"]; 

編輯:

OP想知道如何創建一個cookie。因此,這裏是一些代碼

NSDictionary *cookieProperties = [NSDictionary dictionaryWithObjectsAndKeys: 
         @"domain.com", NSHTTPCookieDomain, 
         @"\\", NSHTTPCookiePath, 
         @"myCookie", NSHTTPCookieName, 
         @"1234", NSHTTPCookieValue, 
         nil]; 
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties]; 
NSArray* cookieArray = [NSArray arrayWithObject:cookie]; 
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray]; 
[request setAllHTTPHeaderFields:headers]; 
+0

謝謝,但我不想讓他們失望。對於「myCookie」,我必須填寫一些內容? – Schmarsi 2012-02-12 17:53:58

+0

我第一次登錄時,我必須創建一個我認爲的cookie。要加載另一個鏈接,我必須發送這個創建的cookie與請求,對不對?我該如何處理? – Schmarsi 2012-02-12 17:55:03

+0

請參閱上面編輯的代碼。 – mbh 2012-02-13 03:53:07

4

不能確定其仍然相關,但萬一有人發現有用的,這裏是你如何發出請求後得到的cookie。

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; 
在此connectionDidFinishLoading

:你應該在被指定作爲代表到NSURLConnection(個體經營你的情況)的對象實現選擇connectionDidFinishLoading:選擇,您可以訪問餅乾這樣的:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSHTTPCookieStorage * storage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; 
    NSArray * cookies = [storage cookiesForURL:connection.currentRequest.URL]; 
    for (NSHTTPCookie * cookie in cookies) 
    { 
     NSLog(@"%@=%@", cookie.name, cookie.value); 
     // Here you can store the value you are interested in for example 
    } 
} 

再後來,該存儲值可以在請求中使用這樣的:

[request setValue:[NSString stringWithFormat:@"%@=%@", cookieName, cookieValue] forHTTPHeaderField:@"Cookie"]; 

或更先進的setAllHTTPHeaderFields:,但請記住在NSHTTPCookiePath字段中使用正確的值,請參閱詳細信息here

NSHTTPCookieStorage也有選擇器-setCookies:forURL:mainDocumentURL:也可用於設置cookie。

2

我有一個WKWebView在初始加載時顯示PHP頁面上的cookie的相同問題,但是當頁面被重新加載/刷新時cookie被清除。以下是我做的工作。

我與cookie設置WKWebView:

WKWebViewConfiguration *webViewConfig = [[WKWebViewConfiguration alloc] init]; // empty for now 
_awesomeWebView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:webViewConfig]; 
_awesomeWebView.UIDelegate = self; 
[self.view addSubview:_awesomeWebView]; 

NSString *url = @"https://phpwebsitewithcookiehandling.com"; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]]; 

// set all the cookies from my NSHTTPCookieStorage in the WKWebView too 
[request setHTTPShouldHandleCookies:YES]; 
[request setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:[NSHTTPCookieStorage sharedHTTPCookieStorage].cookies]]; 

// set the cookie on the initial load 
NSString *cookie = @"status=awesome"; 
[request setValue:cookie forHTTPHeaderField:@"Cookie"]; 
NSLog(@"cookie set in WKwebView header: %@", cookie); 

[_awesomeWebView loadRequest:request]; 

在我phpwebsitewithcookiehandling.com我用下面來驗證它的工作:

<?php 
    echo "<li>status is: " . $_COOKIE['status']; 

    // Here comes the magic which set the servers SET-COOKIE header (apparently) so it works on consecutive page loads 
    setcookie('status', $_COOKIE['status'], time() + (86400 * 30), '/'); 

    echo '<li><a href="">Blank reload</a>'; 
    echo '<li><a href="#" onclick="location.reload(true);">Javascript reload</a>'; 

    exit; 
?> 

它多試錯後,爲我工作。祝你好運。:)

0

沒有源代碼,從NSHTTPURLResponse提取cookie字符串:

static NSString *CookieFromResponse(NSHTTPURLResponse *response) { 
    NSArray<NSHTTPCookie *> *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:response.allHeaderFields forURL:response.URL]; 

    NSMutableString *cookieStr = [NSMutableString string]; 
    for (NSHTTPCookie *cookie in cookies) { 
     if (cookieStr.length) { 
      [cookieStr appendString:@"; "]; 
     } 
     [cookieStr appendFormat:@"%@=%@", cookie.name, cookie.value]; 
    } 
    return cookieStr.length ? cookieStr : nil; 
} 

並以cookie字符串設定爲NSMutableURLRequest

NSString *cookieStr = CookieFromResponse(response); 
[request addValue:cookieStr forHTTPHeaderField:@"Cookie"];