NSURLRequest를 이용하여 웹 페이지의 내용을 받아올 때 서버에서 주는 cookie 정보라던가 content length 등이 필요할 때가 있습니다.
이럴땐 connection:didReceiveResponse: 를 이용하면 손쉽게 데이터를 가공할 수 있습니다.
헤더들을 보기 위해서는 다음과 같이 하시면 됩니다.

1. URL 연결
NSURLConnection *connection;
NSURLRequest *request;

request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://b4you.net"]
                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                       timeoutInterval:60.0f];

connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];


2. delegate에서 호출 될 connection:didReceiveResponse: 메서드 구현 (NSURLConnectionDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse
{
    NSArray *cookies;
    NSDictionary *responseHeaderFields;
    
    // 받은 header들을 dictionary형태로 받고
    responseHeaderFields = [(NSHTTPURLResponse *)aResponse allHeaderFields];
    
    if(responseHeaderFields != nil)
    {
        // responseHeaderFields에 포함되어 있는 항목들 출력
        for(NSString *key in responseHeaderFields)
        {
            NSLog(@"Header: %@ = %@", key, [responseHeaderFields objectForKey:key]);
        }
        
        // cookies에 포함되어 있는 항목들 출력
        cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:responseHeaderFields forURL:[aResponse URL]];
        
        if(cookies != nil)
        {
            for(NSHTTPCookie *a in cookies)
            {
                NSLog(@"Cookie: %@ = %@", [a name], [a value]);
            }
        }
    }
}


3. 나머지 메서드 구현 (NSURLConnectionDelegate)

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"Received: %d", [data length]);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@", [error localizedDescription]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
}


실행하시면 헤더와 쿠키 정보가 출력됩니다.
크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/07/03 14:32 2009/07/03 14:32
, , , ,
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/232


블로그 이미지

빗소리를 먹는 사람.

- 장현준

Notices

Archives

Authors

  1. 장현준

Recent Trackbacks

  1. 듀얼클러치의 생각 rsvin28's me2DAY 2009

Calendar

«   2012/02   »
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29      

Site Stats

Total hits:
158025
Today:
95
Yesterday:
228