如何获得HTTP头(How to get HTTP headers)

2019-07-03 14:10发布

你如何检索来自所有HTTP头NSURLRequest在Objective-C?

Answer 1:

这个属于很容易,但不明显类的iPhone编程问题下。 值得一快速开机的:

为HTTP连接标头包含在NSHTTPURLResponse类。 如果你有一个NSHTTPURLResponse变量,您可以轻松获得头作为一个NSDictionary通过发送allHeaderFields消息。

对于同步请求-不推荐,因为他们阻止-这是很容易来填充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]);
}
}


Answer 2:

鉴于NSURLConnection是从iOS的9弃用,你可以使用NSURLSession从一个获取MIME类型的信息NSURLNSURLRequest

你问的会话中获取的网址,然后在接收到第一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()
}

我已经在打包的类似功能URLEnquiry在GitHub上的项目,这使得它更容易一点,使在线查询的MIME类型和HTTP头。 URLEnquiry.swift是可以被丢弃到自己的项目中的权益的文件。



Answer 3:

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]);
}


Answer 4:

使用Alamofire效率斯威夫特版本。 这是对我工作:

Alamofire.request(YOUR_URL).responseJSON {(data) in

if let val = data.response?.allHeaderFields as? [String: Any] {
      print("\(val)")
    }
}


文章来源: How to get HTTP headers