2017-04-07 42 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