2012-02-12 32 views
11

Tôi đang cố gắng tạo thông tin đăng nhập trong Ứng dụng iPhone của mình.Cách đặt Cookie bằng NSURLRequest?

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]; 

Đó là cách tôi đăng dữ liệu lên Máy chủ, nó hoạt động - tôi nhận được phản hồi. Vấn đề là, đáp ứng là mã của bên đăng nhập, không phải là mã của khu vực "đã lưu". Tôi nghĩ rằng tôi phải tạo cookie để trang web biết rằng tôi đã đăng nhập.

Tôi đã tìm kiếm trên Internet nhưng không thấy bất kỳ điều gì hữu ích. Vậy làm cách nào để tạo cookie, khi tôi đăng nhập vào? Tôi có phải đăng cookie này mọi lúc không, khi tôi đi đến một liên kết khác trong khu vực "đã lưu"?

Hy vọng bạn hiểu được vấn đề của mình.

Greetz

+0

Bạn nên thay đổi câu hỏi của bạn để "Làm thế nào để có được một Cookie với NSURLRequest? " kể từ khi bạn nói rằng bạn muốn có được cookie hiện tại không tạo ra một cookie mới. – Maziyar

Trả lời

27

Hãy thử điều này

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

Edit:

OP muốn biết làm thế nào để tạo ra một cookie. Vì vậy, đây là một số mã số

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

Cảm ơn, nhưng tôi không hiểu. Đối với "myCookie" tôi phải điền vào một cái gì đó? – Schmarsi

+0

Lần đầu tiên tôi đăng nhập, tôi phải tạo một cookie mà tôi nghĩ. Để tải một liên kết khác, tôi phải gửi cookie đã tạo này cùng với yêu cầu, đúng không? Làm cách nào để xử lý việc này? – Schmarsi

+0

Xem mã đã chỉnh sửa ở trên. – mbh

4

không chắc chắn nó vẫn còn phù hợp, dưới đây là cách bạn nhận được cookie sau khi đưa ra yêu cầu. Bạn nên thực hiện các selector connectionDidFinishLoading: trong đối tượng được quy định như một đại biểu để NSURLConnection (tự trong trường hợp của bạn):

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

trong connectionDidFinishLoading này: chọn bạn có thể truy cập các tập tin cookie như thế:

- (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 
    } 
} 

sau đó, giá trị được lưu trữ này có thể được sử dụng trong các yêu cầu như thế này:

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

hoặc cao cấp hơn setAllHTTPHeaderFields:, nhưng hãy nhớ sử dụng giá trị chính xác trong trường NSHTTPCookiePath, xem chi tiết here

cũng NSHTTPCookieStorage có công cụ chọn -setCookies:forURL:mainDocumentURL: cũng có thể được sử dụng để đặt cookie.

2

Tôi đã gặp vấn đề tương tự với WKWebView hiển thị cookie trên trang PHP khi tải ban đầu nhưng cookie đã bị xóa khi trang được tải lại/làm mới. Đây là những gì tôi đã làm để làm cho nó hoạt động.

WKWebView của tôi với các thiết lập cookie:

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]; 

On phpwebsitewithcookiehandling.com của tôi, tôi sử dụng sau đây để xác minh nó làm việc:

<?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; 
?> 

Nó làm việc cho tôi sau nhiều thử và sai. Chúc may mắn.:)

0

Có mã nguồn để trích xuất chuỗi cookie từ NSHTTPURLResponse:

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; 
} 

Và để thiết lập chuỗi cookie NSMutableURLRequest:

NSString *cookieStr = CookieFromResponse(response); 
[request addValue:cookieStr forHTTPHeaderField:@"Cookie"]; 
Các vấn đề liên quan