Objective C асинхронный веб-запрос с cookie

Я нашел решение своей проблемы. У меня многоуровневая архитектура, поэтому мне нужно было создать новый модуль маршрутизации только для ошибок и добавить его, добавив конец моих других модулей маршрутизации.

9
задан Akash Kava 1 April 2009 в 10:49
поделиться

3 ответа

Есть хороший пример использования NSURLRequest и NSHTTPCookies для выполнения полного примера веб-приложения для входа на веб-сайт, сохранения файла cookie SessionID и повторной отправки его в будущих запросах.

NSURLConnection, NSHTTPCookie

Автор 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]);
29
ответ дан 4 December 2019 в 06:02
поделиться

Для асинхронных запросов необходимо использовать NSURLConnection.

Для cookie посмотрите NSHTTPCookie и NSHTTPCookieStorage.

ОБНОВЛЕНИЕ:

Код ниже является реальным, рабочим кодом из одного из моих приложений. responseData определяется как NSMutableData* в интерфейсе класса.

- (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];
}
18
ответ дан 4 December 2019 в 06:02
поделиться

Я могу получить файл cookie таким способом:

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

Этот файл также отлично подходит для асинхронного запроса.

3
ответ дан 4 December 2019 в 06:02
поделиться
Другие вопросы по тегам:

Похожие вопросы: