는 웹 사이트에 로깅 세션 ID 쿠키를 저장하고 향후 요청에 다시 제출의 전체 웹 애플리케이션 예제를 할 NSURLRequest 및 NSHTTPCookies를 사용하는 좋은 사례가있다. logix812으로
NSURLConnection, NSHTTPCookie
:
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]);
여기에 많은 감사합니다! – Hamy
어떻게 비동기입니까 ??? –
답장을 보내 주셔서 감사합니다. 질문이 있지만, 귀하는 [this] (http : //temp/gomh/authenticate.py? setCookie = 1) URL을 제공 한 첫 번째 URL과 두 번째 URL에 대해 서로 다른 URL을 지정했습니다. 하나의 http : // temp 등등. 내 앱에서 사용중인 웹 서비스가이 정보를 제공하지 않았기 때문에 쿠키의 URL을 어떻게 알 수 있습니까? – Hamid