带有 Cookie 的 Objective-C 异步 Web 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/704985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective-C Asynchronous Web Request with Cookies
提问by Akash Kava
I am writing a program in Objective-C and I need to make web requests to web server, but asynchronously and I am fairly new on mac, I am very good at windows technologies, but I need to know that if I use NSOperation (introduced in 10.5, i am assuming that it will not run in 10.4 MAC?), or if it was implemented such that it utilizes system threading which will be available on 10.4?
我正在用 Objective-C 编写一个程序,我需要向 Web 服务器发出 Web 请求,但我是异步的,而且我在 mac 上还是个新手,我非常擅长 Windows 技术,但是我需要知道,如果我使用 NSOperation(引入在 10.5 中,我假设它不会在 10.4 MAC 中运行?),或者它是否被实现为利用了在 10.4 上可用的系统线程?
Or I should create a new thread and create a new runloop, also how to use cookies etc, if anyone can give me one small example, that will be of great help. I want this sample to run on mac 10.4 too if possible.
或者我应该创建一个新线程并创建一个新的runloop,以及如何使用cookie等,如果有人能给我一个小例子,那将有很大帮助。如果可能,我也希望此示例也能在 mac 10.4 上运行。
回答by Dougnukem
There's a good example of using NSURLRequest and NSHTTPCookies to do a full web application example of logging into a website, storing the SessionID cookie and resubmitting it in future requests.
有一个使用 NSURLRequest 和 NSHTTPCookies 来完成登录网站、存储 SessionID cookie 并在以后的请求中重新提交的完整 Web 应用程序示例的一个很好的示例。
By logix812:
通过 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]);
回答by Can Berk Güder
For asynchronous requests, you need to use NSURLConnection.
对于异步请求,您需要使用NSURLConnection.
For cookies, see NSHTTPCookieand NSHTTPCookieStorage.
对于 cookie,请参阅NSHTTPCookie和NSHTTPCookieStorage。
UPDATE:
更新:
The code below is real, working code from one of my applications. responseDatais defined as NSMutableData*in the class interface.
下面的代码是来自我的一个应用程序的真实工作代码。在类接口中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];
}
回答by tdu
I am able to fetch cookie in such way:
我能够以这种方式获取 cookie:
NSArray* arr = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString: @"http://google.com" ]];
This one works fine for asynchronous request as well.
这个也适用于异步请求。

