【问题标题】:Objective-C Asynchronous Web Request with Cookies带有 Cookie 的 Objective-C 异步 Web 请求
【发布时间】:2010-10-16 20:10:31
【问题描述】:

我正在用 Objective-C 编写一个程序,我需要向 web 服务器发出 web 请求,但是异步的,我在 mac 上相当新,我非常擅长 windows 技术,但我需要知道如果我使用NSOperation(在 10.5 中引入,我假设它不会在 10.4 MAC 中运行?),或者如果它被实现为利用 10.4 上可用的系统线程?

或者我应该创建一个新线程并创建一个新的runloop,以及如何使用cookie等,如果有人能给我一个小例子,那将有很大帮助。如果可能的话,我希望这个示例也能在 mac 10.4 上运行。

【问题讨论】:

    标签: objective-c multithreading macos asynchronous


    【解决方案1】:

    有一个很好的例子,使用 NSURLRequest 和 NSHTTPCookies 来做一个完整的 web 应用程序示例,登录到一个网站,存储 SessionID cookie 并在以后的请求中重新提交它。

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

    【讨论】:

    • 感谢您的回答,但我有一个问题,您指定了不同的 URL,例如您提供的第一个 [this] (temp/gomh/authenticate.py?setCookie=1) URL 和第二个 temp 和很快。我如何知道 cookie 的 URL,因为我在我的应用程序中使用的网络服务没有提供此信息?
    【解决方案2】:

    对于异步请求,需要使用NSURLConnection

    有关 Cookie,请参阅 NSHTTPCookieNSHTTPCookieStorage

    更新:

    下面的代码是来自我的一个应用程序的真实有效代码。 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];
    }
    

    【讨论】:

    • @Akash: 你试过 NSURLConnection 的 connectionWithRequest:delegate: 方法吗?很抱歉,您的问题中没有提到 NSURLConnection 或 NSHTTPCookie 。相信我,您需要的一切都在我提供的链接中。
    • 我已经用过它了,它不起作用所以我认为必须有其他方法来执行异步请求,因为没有任何示例代码可以做到这一点。这是我尝试过的代码.. stackoverflow.com/questions/706355/…
    • @Akash:NSURLConnection 是最简单的方法。我将发布示例代码。
    【解决方案3】:

    我可以通过这种方式获取 cookie:

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

    这也适用于异步请求。

    【讨论】:

      猜你喜欢
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 2013-10-23
      相关资源
      最近更新 更多