如何获取HTTP标头
答
这符合简单,但不明显类的iPhone编程问题。值得快速发布:
类中包含HTTP连接的标头。如果您有NSHTTPURLResponse
变量,则可以通过发送allHeaderFields消息轻松地将标题作为NSDictionary
取出。
对于同步请求 - 不推荐,因为他们阻止 - 这是很容易来填充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
像这样:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
NSLog([dictionary description]);
}
}
答
YourViewController.h
@interface YourViewController : UIViewController <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *yourWebView;
@end
YourViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
//Set the UIWebView delegate to your view controller
self.yourWebView.delegate = self;
//Request your URL
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://website.com/your-page.php"]];
[self.legalWebView loadRequest:request];
}
//Implement the following method
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSLog(@"%@",[webView.request allHTTPHeaderFields]);
}
答
鉴于NSURLConnection
从iOS的9弃用,你可以使用一个NSURLSession
获得从NSURL
或NSURLRequest
MIME类型的信息。
您要求会话检索URL,然后在代理回调中收到第一个NSURLResponse
(其中包含MIME类型信息)时,您取消会话以阻止其下载整个URL。
下面是一些裸露的骨头斯威夫特代码做的:
/// Use an NSURLSession to request MIME type and HTTP header details from URL.
///
/// Results extracted in delegate callback function URLSession(session:task:didCompleteWithError:).
///
func requestMIMETypeAndHeaderTypeDetails() {
let url = NSURL.init(string: "https://google.com/")
let urlRequest = NSURLRequest.init(URL: url!)
let session = NSURLSession.init(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())
let dataTask = session.dataTaskWithRequest(urlRequest)
dataTask.resume()
}
//MARK: NSURLSessionDelegate methods
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
// Cancel the rest of the download - we only want the initial response to give us MIME type and header info.
completionHandler(NSURLSessionResponseDisposition.Cancel)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?)
{
var mimeType: String? = nil
var headers: [NSObject : AnyObject]? = nil
// Ignore NSURLErrorCancelled errors - these are a result of us cancelling the session in
// the delegate method URLSession(session:dataTask:response:completionHandler:).
if (error == nil || error?.code == NSURLErrorCancelled) {
mimeType = task.response?.MIMEType
if let httpStatusCode = (task.response as? NSHTTPURLResponse)?.statusCode {
headers = (task.response as? NSHTTPURLResponse)?.allHeaderFields
if httpStatusCode >= 200 && httpStatusCode < 300 {
// All good
} else {
// You may want to invalidate the mimeType/headers here as an http error
// occurred so the mimeType may actually be for a 404 page or
// other resource, rather than the URL you originally requested!
// mimeType = nil
// headers = nil
}
}
}
NSLog("mimeType = \(mimeType)")
NSLog("headers = \(headers)")
session.invalidateAndCancel()
}
我已经在GitHub上的URLEnquiry项目,这使得它更容易一点,使在线查询的MIME类型和包装相似的功能HTTP标头。 URLEnquiry.swift是可以放入您自己的项目中的感兴趣的文件。
答
使用Alamofire实现效率的Swift版本。这对我来说很有效:
Alamofire.request(YOUR_URL).responseJSON {(data) in
if let val = data.response?.allHeaderFields as? [String: Any] {
print("\(val)")
}
}
如果你只是想获取http响应头然后发布HEAD请求。 HEAD请求不会获取响应主体。 示例 - 请求中设置Http方法类型。 NSMutableURLRequest * mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url]; mutableRequest.HTTPMethod = @“HEAD”; – Omkar
为什么我们应该将NSURLResponse强制转换为NSHTTPURLResponse? – youssman
这不会*记录请求中发送的所有头文件!如果您将其他标头设置为NSURLSessionConfiguration,则不会记录这些标头。我还没有找到如何从响应中检索它们... – Johanneke