2017-04-02 119 views
-2

我想從http://random.cat/得到隨機的圖片,所以我想用Directory.GetFiles或類似的東西來索引它們,但這不起作用。那麼得到Directory.GetFiles的功能的最好方法是什麼,但是對於http://random.cat/i(我認爲這是存儲圖像的地方)?從網頁目錄下載文件

在此先感謝!

回答

0

沒有訪問到圖像數據庫,但它們提供了一次檢索一個圖像的api。

創建一個基本模型:

public class RandomImage 
{ 
    public string file { get; set; } 
} 

然後你可以使用Web客戶端來做到這一點:

public string RandomImage() 
{ 
    string result = null; 

    var apiurl = "http://random.cat"; 

    HttpClient client = new HttpClient(); 
    client.BaseAddress = new Uri(apiurl); 
    client.DefaultRequestHeaders.Accept.Clear(); 
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

    HttpResponseMessage ResponseMessage = client.GetAsync(apiurl + "/meow").Result; // The .Result part will make this method not async 
    if (ResponseMessage.IsSuccessStatusCode) 
    { 
     var ResponseData = ResponseMessage.Content.ReadAsStringAsync().Result; 
     var MyRandomImage = JsonConvert.DeserializeObject<RandomImage>(ResponseData); 

     result = MyRandomImage.file; // This is the url for the file 
    } 

    // Return 
    return result; 
} 

呼叫從自己的方法的功能:

var MyImage = RandomImage(); 
+0

非常感謝!那是,我的問題是! – LordOsslor

0

Directory.GetFiles()被設計成在文件系統上使用,而不是在網址上使用。

This link應該足以讓你開始。由於您不知道圖片的實際網址,因此您需要parse the page to find it,然後再提出下載請求。

請注意,如果您在特定時間內下載過多圖片,他們可能會阻止您。

編輯:我剛纔注意到他們有一個API,這使得一切都變得更簡單。但它被標記爲暫時的,所以你要做的就是這樣。

0

如前所述,您必須使用HttpClient。我不知道列出所有文件的方法,但這也需要在託管該站點的Web服務器中設置。