如何获取HTTP标头

如何获取HTTP标头

本文介绍了如何获取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标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 05:32