如何获取 HTTP 标头 [英] How to get HTTP headers

查看:33
本文介绍了如何获取 HTTP 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 Objective-C 中的 NSURLRequest 中检索所有 HTTP 标头?

How do you retrieve all HTTP headers from a NSURLRequest in Objective-C?

推荐答案

这属于简单但不明显的 iPhone 编程问题类.值得快速发帖:

This falls under the easy, but not obvious class of iPhone programming problems. Worthy of a quick post:

HTTP 连接的标头包含在 NSHTTPURLResponse 类中.如果您有一个 NSHTTPURLResponse 变量,您可以通过发送 allHeaderFields 消息轻松地将标头作为 NSDictionary 获取.

The headers for an HTTP connection are included in the NSHTTPURLResponse class. If you have an NSHTTPURLResponse variable you can easily get the headers out as a NSDictionary by sending the allHeaderFields message.

对于同步请求——不推荐,因为它们会阻塞——填充 NSHTTPURLResponse 很容易:

For synchronous requests — not recommended, because they block — it’s easy to populate an NSHTTPURLResponse:

NSURL *url = [NSURL URLWithString:@"http://www.mobileorchard.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]);
}

对于异步请求,您必须做更多的工作.当回调 connection:didReceiveResponse: 被调用时,它被传递一个 NSURLResponse 作为第二个参数.您可以将其转换为 NSHTTPURLResponse,如下所示:

With an asynchronous request you have to do a little more work. When the callback connection:didReceiveResponse: is called, it is passed an NSURLResponse as the second parameter. You can cast it to an NSHTTPURLResponse like so:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;    
if ([response respondsToSelector:@selector(allHeaderFields)]) {
    NSDictionary *dictionary = [httpResponse allHeaderFields];
    NSLog([dictionary description]);
}
}

这篇关于如何获取 HTTP 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆