2012-11-05 44 views

Trả lời

32

này thuộc dễ dàng, nhưng không rõ ràng lớp của các vấn đề lập trình iPhone. Xứng đáng với bài đăng nhanh:

Tiêu đề cho kết nối HTTP được bao gồm trong lớp NSHTTPURLResponse. Nếu bạn có biến số NSHTTPURLResponse, bạn có thể dễ dàng lấy tiêu đề ra dưới dạng NSDictionary bằng cách gửi thông báo allHeaderFields.

Đối với yêu cầu đồng bộ - không được khuyến khích, bởi vì họ chặn - nó dễ dàng để cư một 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]); 
} 

Với một yêu cầu không đồng bộ bạn phải làm một công việc ít hơn. Khi gọi lại connection:didReceiveResponse: được gọi, nó được chuyển thông số NSURLResponse làm thông số thứ hai. Bạn có thể bỏ nó vào một NSHTTPURLResponse như vậy:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;  
if ([response respondsToSelector:@selector(allHeaderFields)]) { 
    NSDictionary *dictionary = [httpResponse allHeaderFields]; 
    NSLog([dictionary description]); 
} 
} 
+3

Nếu bạn chỉ muốn tìm nạp tiêu đề phản hồi http, sau đó đăng yêu cầu HEAD. Yêu cầu HEAD sẽ không tìm nạp nội dung phản hồi. Ví dụ - Đặt loại Phương thức Http theo yêu cầu. NSMutableURLRequest * mutableRequest = [[NSMutableURLRequest alloc] initWithURL: url]; mutableRequest.HTTPMethod = @ "HEAD"; – Omkar

+0

Tại sao chúng ta nên đưa NSURLResponse vào NSHTTPURLResponse? – youssman

+0

Điều này không * ghi * tất cả các tiêu đề được gửi trong yêu cầu! Nếu bạn đặt tiêu đề bổ sung cho NSURLSessionConfiguration, những tiêu đề đó sẽ không được ghi lại. Tôi chưa tìm được cách lấy chúng từ phản hồi ... – Johanneke

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

Với NSURLConnection bị phản đối từ iOS 9, bạn có thể sử dụng một NSURLSession để có được kiểu MIME thông tin từ một NSURL hoặc NSURLRequest.

Bạn yêu cầu phiên truy xuất URL, sau đó khi nhận được NSURLResponse đầu tiên (có chứa thông tin loại MIME) trong cuộc gọi đại biểu, bạn hủy phiên để ngăn tải xuống toàn bộ URL.

Dưới đây là một số xương trần đang Swift nào đó:

/// 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() 
} 

Tôi đã đóng gói chức năng tương tự trong dự án URLEnquiry tại github mà làm cho nó một chút dễ dàng hơn để thực hiện các truy vấn trong-line với nhiều loại MIME và Tiêu đề HTTP. URLEnquiry.swift là tệp quan tâm có thể được đưa vào dự án của riêng bạn.

1

Phiên bản Swift sử dụng Alamofire để có hiệu quả. Đây là những gì đã làm việc cho tôi:

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

if let val = data.response?.allHeaderFields as? [String: Any] { 
     print("\(val)") 
    } 
} 
Các vấn đề liên quan