2011-08-31 70 views
11

一個簡短的問題。我有以下的代碼獲得一個服務器上的文件的MOD日期:iOS - 獲取標題結果

- (void) sendRequestForLastModifiedHeaders 
{ 
    /* send a request for file modification date */ 
    NSURLRequest *modReq = [NSURLRequest requestWithURL:[NSURL URLWithString:URLInput.text] 
             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f]; 
    [[NSURLConnection alloc] initWithRequest:modReq delegate:self]; 
} 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    /* convert response into an NSHTTPURLResponse, 
    call the allHeaderFields property, then get the 
    Last-Modified key. 
    */ 

    NSHTTPURLResponse *foo = [(NSHTTPURLResponse *)response allHeaderFields]; 

    NSString * last_modified = [NSString stringWithFormat:@"%@", 
          [[(NSHTTPURLResponse *)response allHeaderFields] objectForKey:@"Last-Modified"]]; 

    NSLog(@"Last-Modified: %@", last_modified); 

} 

我的主要問題是:

這是否調用只發送了頭?如果文件很大,我不希望整個文件被下載。這就是我檢查標題的原因。

+++++++++++++++++++++++ 更新後可以使用。 .. 感謝現在的樣子:

NSMutableURLRequest *modReq = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:    URLInput.text] 
             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f]; 
[modReq setHTTPMethod:@"HEAD"]; 
+0

您是否正在檢查最後修改的標題,以確定是否需要下載文件的新副本?如果是這樣的話,我會建議使用一個預製的HTTP請求庫,其中包含了所有這些內容,例如['ASIHTTPRequest'](http://allseeing-i.com/ASIHTTPRequest)。您可以在那裏設置的各種緩存策略應該適合您的情況。 – darvids0n

+0

想了解更多關於HTTP如何工作的信息,請參閱[RFC 2616](http://tools.ietf.org/html/rfc2616)。第9節定義了各種方法GET,HEAD,POST等。除了這三種方法以外,其他方法很少使用。 –

+0

@iOSGuy你在推特上嗎? – MarkP

回答

27

正如你現在擁有它,你可能會下載整個文件。關鍵是用於http請求的http方法。默認情況下,它是一個GET請求。你想要的是一個HEAD請求。你不需要這個文件,你只想讓服務器返回你會得到的迴應,對吧?

要做到這一點,您需要使用NSMutableURLRequestsetHTTPMethod:來構建一個使用HEAD而不是GET的方法的請求。

+0

謝謝...讓生活更輕鬆... – iOSGuy

+0

@iOSGuy:請點擊旁邊的複選標記以接受此答案。 – darvids0n