2012-02-12 14 views
11

Sto provando a creare un accesso nella mia app per iPhone.Come impostare un cookie con 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]; 

Questo è il modo in cui ho posto i miei dati al server, funziona - ottengo una risposta. Il problema è che la risposta è il codice del lato login, non il codice dell'area "salvata". Penso di dover creare i cookie, in modo che il sito Web sappia che sono connesso.

Ho cercato su Internet ma non ho trovato nulla di utile. Quindi, come faccio a creare un cookie quando mi registro? Devo pubblicare questo cookie ogni volta, quando vado a un altro link nell'area "salvata"?

Spero che tu abbia capito il mio problema.

Greetz

+0

si dovrebbe cambiare la tua domanda a "Come ottenere un biscotto con un NSURLRequest? " dato che hai detto che vuoi ottenere il cookie esistente senza crearne uno nuovo. – Maziyar

risposta

27

Prova questa

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

Edit:

OP vuole sapere come creare un cookie. Così qui è un codice

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

Grazie, ma non lo comprendo. Per "myCookie" devo compilare qualcosa? – Schmarsi

+0

La prima volta che accedo, devo creare un cookie che ho pensato. Per caricare un altro link devo inviare questo cookie creato con la richiesta, giusto? Come gestisco questo? – Schmarsi

+0

Vedere il codice modificato sopra. – mbh

4

non sicuro che sia ancora rilevante, ma nel caso in cui qualcuno scoprire che utile, ecco come si ottiene il cookie dopo aver fatto una richiesta. Si dovrebbe implementare il selettore connectionDidFinishLoading: nell'oggetto che è stato specificato come delegato al NSURLConnection (auto nel tuo caso):

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

in questo connectionDidFinishLoading: selettore è possibile accedere ai cookie di simile:

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

poi, questo valore memorizzato può essere usato in domande come questa:

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

o più avanzato setAllHTTPHeaderFields:, ma ricordarsi di utilizzare il valore corretto nella NSHTTPCookiePath campo, vedere i dettagli here

anche NSHTTPCookieStorage ha selettore -setCookies:forURL:mainDocumentURL: che può anche essere utilizzato per impostare i cookie.

2

Ho avuto lo stesso problema con un WKWebView che mostra il cookie su una pagina PHP al caricamento iniziale ma il cookie è stato cancellato quando la pagina è stata ricaricata/aggiornata. Ecco cosa ho fatto per farlo funzionare.

mio WKWebView con l'impostazione dei 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]; 

Sul mio phpwebsitewithcookiehandling.com ho usato il seguente per verificare che ha funzionato:

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

Ha funzionato per me dopo molti tentativi ed errori. In bocca al lupo.:)

0

C'è il codice sorgente per estrarre stringhe cookie dal 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; 
} 

E per impostare stringa di cookie per NSMutableURLRequest:

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