2017-04-07 94 views
0

我想從這個網址http://squirlytraffic.com/surficon.php?ts=1491591235C#下載圖像,而不擴展

下載圖像,我想這個代碼,但我沒有看到圖像,當我打開它。

using (WebClient client = new WebClient()) 
    { 
    client.DownloadFile("http://squirlytraffic.com/surficon.php?ts=1491591235", @"D:\image.jpg");   
    } 
+0

的URL重定向到登錄,您需要驗證這些參數傳遞在您下載圖片之前 – Krishna

+0

我在網頁瀏覽器中登錄。 – szanex

+0

不,你必須從網絡客戶端 – Krishna

回答

0

您需要使用WebClient Credentials屬性設置您的憑據。您可以通過爲其分配NetworkCredential的實例來完成此操作。請看下圖:

using (WebClient client = new WebClient()){ 
    client.Credentials = new NetworkCredential("user-name", "password"); 
    client.DownloadFile("url", @"file-location"); 
} 

編輯

如果你不想硬編碼用戶名和密碼,您可以在Web客戶端的UseDefaultCredentials屬性設置爲true。這將使用當前登錄用戶的憑證。從documentation

Credentials屬性包含用於訪問主機上資源的認證憑證。在大多數客戶端場景中,您應該使用DefaultCredentials,這是當前登錄用戶的憑據。爲此,請將UseDefaultCredentials屬性設置爲true,而不是設置此屬性。

這將意味着你可以修改上面的代碼:

using (WebClient client = new WebClient()){ 
    client.UseDefaultCredentials = true; 
    client.DownloadFile("url", @"file-location"); 
} 
0

嘗試這種方式,當登錄

  StringBuilder postData = new StringBuilder(); 
      postData.Append("login=" + HttpUtility.UrlEncode("username") + "&"); 
      postData.Append("password=" + HttpUtility.UrlEncode("password") + "&"); 
      postData.Append("Submit=" + HttpUtility.UrlEncode("Login")); 
      ASCIIEncoding ascii = new ASCIIEncoding(); 
      byte[] postBytes = ascii.GetBytes(postData.ToString()); 
      CookieContainer cc = new CookieContainer(); 
      HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create("http://squirlytraffic.com/members.php"); 
      webReq.Method = "POST"; 
      webReq.ContentType = "application/x-www-form-urlencoded"; 
      webReq.ContentLength = postBytes.Length; 
      webReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; 
      webReq.CookieContainer = cc; 
      Stream postStream = webReq.GetRequestStream(); 
      postStream.Write(postBytes, 0, postBytes.Length); 
      postStream.Flush(); 
      postStream.Close(); 
      HttpWebResponse res = (HttpWebResponse)webReq.GetResponse(); 
      HttpWebRequest ImgReq = (HttpWebRequest)WebRequest.Create("http://squirlytraffic.com/surficon.php?ts=1491591235"); 
      ImgReq.Method = "GET"; 
      ImgReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; 
      ImgReq.CookieContainer = cc; 
      HttpWebResponse ImgRes = (HttpWebResponse)ImgReq.GetResponse(); 
      Stream Img = ImgRes.GetResponseStream(); 
+0

不起作用。如何檢查我是否使用webrequest登錄? – szanex

+0

如果此代碼下載圖像,我可以在哪裏找到驅動器中的圖像? – szanex

+0

登錄後,響應HTML將顯示一個登錄後頁面,上面的代碼只是檢索您需要將該流寫入文件的流 – Krishna