使用Cookie的Objective-C异步Web请求

9
我正在用Objective-C编写程序,需要异步与Web服务器进行网络请求。尽管我在Windows技术方面很擅长,但我对Mac还比较生疏。请问NSOperation(从10.5开始引入)是否能够在10.4上运行?或者它是否采用了系统线程,在10.4上可用?
如果不行,我是否应该创建一个新的线程并创建一个新的运行循环?此外,如何使用cookie等内容?如果有人能给我一个小例子,将会非常有帮助。最好能在Mac 10.4上运行。
3个回答

29

这里有一个很好的示例,展示如何使用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]);

1
谢谢您的回答,但我有一个问题。您为不同的URL指定了示例,例如您提供了此URL:[http://temp/gomh/authenticate.py?setCookie=1],而对于第二个URL,您提供了http://temp等等。由于我使用的应用程序中的Web服务没有提供此信息,我该如何知道Cookie的URL? - Hamid

18

对于异步请求,您需要使用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];
}

1
@Akash:你试过使用NSURLConnection的connectionWithRequest:delegate:方法吗?很抱歉,但我在你的问题中没有看到任何关于NSURLConnection或NSHTTPCookie的提及。相信我,我给出的链接中包含了你需要的一切。 - Can Berk Güder
我已经尝试使用它,但没能奏效,所以我认为肯定有其他方法来进行异步请求,因为没有样例代码可以执行。 这是我尝试的代码...http://stackoverflow.com/questions/706355/whats-wrong-on-following-urlconnection - Akash Kava
@Akash:NSURLConnection是最简单的方法。我会发布样例代码。 - Can Berk Güder

3
我可以这样获取Cookie:

我能够以这种方式获取cookie:

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

这个也适用于异步请求,没有问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接