NSURLRequest获取Header

与http交互的时候,尤其是下载东西的时候,header有很多有用的信息哟,so,这里是方法
同步访问时的取法

NSURL *url = [NSURL URLWithString:@"http://www.test.com"];
NSURLRequest *request = [NSURLRequest requestWithURL: url];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest: request returningResponse: &response error: nil];
if ([response respondsToSelector:@selector(allHeaderFields)]) {
    // 取得所有的请求的头
    NSDictionary *dictionary = [response allHeaderFields];
    NSLog([dictionary description]);
    // 取得http状态码
    NSLog(@"%d",[response statusCode]);
}

异步访问时则要实现委托的一个方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // 注意这里将NSURLResponse对象转换成NSHTTPURLResponse对象才能去
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
    if ([response respondsToSelector:@selector(allHeaderFields)]) {
        NSDictionary *dictionary = [httpResponse allHeaderFields];
        NSLog([dictionary description]);
        NSLog(@"%d",[response statusCode]);
    }
}

摘自:iPhone开发:通过NSURLRequest获得服务器返回的http header和http status

转载请注明: 转自Rainbird的个人博客
   本文链接: NSURLRequest获取Header


相关博文

    分享到:

About rainbird

IOS攻城狮
This entry was posted in IOS开发, Mac开发, object-c and tagged , , , , , , , . Bookmark the permalink.

发表评论