简体   繁体   中英

Reading data from response header of NSURLConnection

How can I read the data from the header sent by in the server response. I am using NSURLConnection to send the request.

If the URL is an HTTP URL, then the NSURLResponse that you receive in your connection's delegate's -connection:didReceiveResponse: method (or via another method) will be an NSHTTPURLResponse , which has an -allHeaderFields method that lets you access the headers.

NSURLResponse* response = // the response, from somewhere
NSDictionary* headers = [(NSHTTPURLResponse *)response allHeaderFields];
// now query `headers` for the header you want

In my case

    NSHTTPURLResponse *response = ((NSHTTPURLResponse *)[task response]);
    NSDictionary *headers = [response allHeaderFields];

Good Approach

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)[task response];
    if ([httpResponse respondsToSelector:@selector(allHeaderFields)]) {
         NSDictionary *dictionary = [httpResponse allHeaderFields];
         NSLog(@"%@", [dictionary description]);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM