Objective-C异步Web请求与Cookie
发布时间:2020-12-16 02:59:32 所属栏目:百科 来源:网络整理
导读:我正在Objective-C中编写一个程序,我需要将Web请求发送到Web服务器,但异步地,我在Mac上是相当新的,我非常擅长 windows技术,但是我需要知道,如果我使用NSOperation在10.5中,我假设它不会在10.4 MAC中运行),或者如果它被实现,使用将在10.4上可用的系统线程?
我正在Objective-C中编写一个程序,我需要将Web请求发送到Web服务器,但异步地,我在Mac上是相当新的,我非常擅长
windows技术,但是我需要知道,如果我使用NSOperation在10.5中,我假设它不会在10.4 MAC中运行),或者如果它被实现,使用将在10.4上可用的系统线程?
或者我应该创建一个新的线程,创建一个新的runloop,还有如何使用cookies等,如果有人可以给我一个小例子,那将是很大的帮助.我想要这个样本也可以在mac 10.4上运行. 解决方法
有一个很好的例子,使用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]); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |