2009-04-01 11 views
9

Sto scrivendo un programma in Objective-C e devo fare richieste web al web server, ma in modo asincrono e sono abbastanza nuovo su mac, sono molto bravo con le tecnologie windows, ma Devo sapere che se uso NSOperation (introdotto in 10.5, presumo che non funzionerà in MAC 10.4), o se è stato implementato in modo tale che utilizzi il threading del sistema che sarà disponibile su 10.4?Richiesta Web asincrona Objective-C con i cookie

Oppure dovrei creare un nuovo thread e creare un nuovo runloop, anche come usare i cookie ecc., Se qualcuno può darmi un piccolo esempio, sarà di grande aiuto. Voglio che questo esempio venga eseguito anche su mac 10.4 se possibile.

risposta

29

C'è un buon esempio di utilizzo NSURLRequest e NSHTTPCookies per fare un esempio completo di applicazioni web di accedere in un sito web, memorizzare il cookie SessionID e ripresentarlo a richieste future.

NSURLConnection, NSHTTPCookie

By logix812:

NSHTTPURLResponse * response; 
    NSError    * error; 
    NSMutableURLRequest * request; 
    request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://temp/gomh/authenticate.py?setCookie=1"] 
              cachePolicy:NSURLRequestReloadIgnoringCacheData 
             timeoutInterval:60] autorelease]; 

    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    NSLog(@"RESPONSE HEADERS: \n%@", [response allHeaderFields]); 

    // If you want to get all of the cookies: 
    NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@"http://temp"]]; 
    NSLog(@"How many Cookies: %d", all.count); 
    // Store the cookies: 
    // NSHTTPCookieStorage is a Singleton. 
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:all forURL:[NSURL URLWithString:@"http://temp"] mainDocumentURL:nil]; 

    // Now we can print all of the cookies we have: 
    for (NSHTTPCookie *cookie in all) 
     NSLog(@"Name: %@ : Value: %@, Expires: %@", cookie.name, cookie.value, cookie.expiresDate); 


    // Now lets go back the other way. We want the server to know we have some cookies available: 
    // this availableCookies array is going to be the same as the 'all' array above. We could 
    // have just used the 'all' array, but this shows you how to get the cookies back from the singleton. 
    NSArray * availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"http://temp"]]; 
    NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies]; 

    // we are just recycling the original request 
    [request setAllHTTPHeaderFields:headers]; 

    request.URL = [NSURL URLWithString:@"http://temp/gomh/authenticate.py"]; 
    error  = nil; 
    response = nil; 

    NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    NSLog(@"The server saw:\n%@", [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease]); 
+0

grazie mille! – Hamy

+0

Com'è che è asincrono ??? –

+1

Grazie per la risposta, ma ho una domanda, hai specificato diversi URL, ad esempio per il primo che hai fornito [questo] (http: //temp/gomh/authenticate.py? SetCookie = 1) URL e per il secondo un http: // temp e così via. Come faccio a sapere l'URL dei cookie, dal momento che il servizio web che sto utilizzando nella mia app non ha fornito queste informazioni? – Hamid

18

Per richieste asincrone, è necessario utilizzare NSURLConnection.

Per i cookie, vedere NSHTTPCookie e NSHTTPCookieStorage.

UPDATE:

Il codice qui sotto è reale, il codice di lavoro da una delle mie applicazioni. responseData è definito come NSMutableData* nell'interfaccia di classe.

- (void)load { 
    NSURL *myURL = [NSURL URLWithString:@"http://stackoverflow.com/"]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:myURL 
              cachePolicy:NSURLRequestReloadIgnoringLocalCacheData 
             timeoutInterval:60]; 
    [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    responseData = [[NSMutableData alloc] init]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [responseData appendData:data]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
    [responseData release]; 
    [connection release]; 
    // Show error message 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    // Use responseData 
    [responseData release]; 
    [connection release]; 
} 
+1

@Akash: hai provato la connessione di NSURLConnectionWithRequest: delegate: method? E mi dispiace ma non vedo menzione di NSURLConnection o NSHTTPCookie nella tua domanda. Fidati di me, tutto ciò di cui hai bisogno è nei link che ho dato. –

+0

L'avevo già usato, non funzionava, quindi ho pensato che ci fosse un altro modo per fare una richiesta asincrona in quanto non esiste alcun codice di esempio per farlo. Ecco il codice che ho provato .. http://stackoverflow.com/questions/706355/whats-wrong-on-following-urlconnection –

+0

@Akash: NSURLConnection è il modo più semplice. Posterò codice di esempio –

3

io sono in grado di recuperare dei cookie in modo tale:

NSArray* arr = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString: @"http://google.com" ]]; 

Questo funziona bene per richiesta asincrona pure.

Problemi correlati