프로가 되자.

post search result

NSURLResponse와 관련된 글 1개를 찾았습니다.

  1. 2009/07/03 NSURLRequest에서 response header 정보 출력하기

NSURLRequest에서 response header 정보 출력하기

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
2009/07/03 14:32 2009/07/03 14:32

top

About this post

이 글에는 아직 트랙백이 없고, 아직 댓글이 없고, , , , , 태그가 달려있으며,
2009/07/03 14:32에 작성되었습니다.

◀ recent : [1] : previous ▶

blog information

프로가 되자.
BLOG main image
빗소리를 먹는 사람.
RSS 2.0Tattertools
최근 글 최근 댓글 최근 트랙백
태그 구름사이트 링크