2012-11-05 173 views

回答

32

這符合簡單,但不明顯類的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]); 
} 
} 
+3

如果你只是想獲取http響應頭然後發佈HEAD請求。 HEAD請求不會獲取響應主體。 示例 - 請求中設置Http方法類型。 NSMutableURLRequest * mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url]; mutableRequest.HTTPMethod = @「HEAD」; – Omkar

+0

爲什麼我們應該將NSURLResponse強制轉換爲NSHTTPURLResponse? – youssman

+0

這不會*記錄請求中發送的所有頭文件!如果您將其他標頭設置爲NSURLSessionConfiguration,則不會記錄這些標頭。我還沒有找到如何從響應中檢索它們... – 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

鑑於NSURLConnection從iOS的9棄用,你可以使用一個NSURLSession獲得從NSURLNSURLRequest 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是可以放入您自己的項目中的感興趣的文件。

1

使用Alamofire實現效率的Swift版本。這對我來說很有效:

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

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