How to get HTTP headers(如何获取 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 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获取 HTTP 标头


基础教程推荐
- Android文本颜色不会改变颜色 2022-01-01
- 在 iOS 上默认是 char 签名还是 unsigned? 2022-01-01
- LocationClient 与 LocationManager 2022-01-01
- 如何使 UINavigationBar 背景透明? 2022-01-01
- :hover 状态不会在 iOS 上结束 2022-01-01
- 固定小数的Android Money Input 2022-01-01
- Android ViewPager:在 ViewPager 中更新屏幕外但缓存的片段 2022-01-01
- “让"到底是怎么回事?关键字在 Swift 中的作用? 2022-01-01
- 如何使用 YouTube API V3? 2022-01-01
- 使用 Ryzen 处理器同时运行 WSL2 和 Android Studio 2022-01-01