Подтвердить что ты не робот

Как получить заголовки HTTP

Как вы извлекаете все HTTP-заголовки из NSURLRequest в Objective-C?

4b9b3361

Ответ 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]);
}
}

Ответ 2

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

Ответ 3

Учитывая, что NSURLConnection устарел из iOS 9, вы можете использовать NSURLSession для получения информации типа MIME из NSURL или NSURLRequest.

Вы запрашиваете сеанс для получения URL-адреса, после получения первого NSURLResponse (который содержит информацию типа MIME) в обратном вызове делегата вы отмените сеанс, чтобы предотвратить его загрузку всего URL-адреса.

Вот несколько костей Swift, которые он делает:

/// 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 - файл, представляющий интерес, который можно было бы удалить в свой собственный проект.

Ответ 4

Быстрая версия с использованием Alamofire для повышения эффективности. Это то, что сработало для меня:

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

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