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 标头
基础教程推荐
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01