使用HttpWebRequest下載圖檔

Designed by Freepik
此篇紀錄如何使用HttpWebRequest下載檔案(照片)
圖片來源Designed by Freepik


程式碼如下
public string DownloadImage(string szURL, string szFilePath, string szFileName)
{
  string sResult = "";

  //網站使用更安全的TLS時,加入以下兩行
  ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
  ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;

  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(szURL);
  request.Method = "GET";   request.Timeout = 30000;

  try
  {

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
      Stream dataStream = response.GetResponseStream();
      byte[] buffer = new byte[8192];
      using (FileStream fs = new FileStream(szFilePath + szFileName, FileMode.Create, FileAccess.Write))
      {
        int size = 0;
        do
        {
          size = dataStream.Read(buffer, 0, buffer.Length);
          if (size > 0)
            fs.Write(buffer, 0, size);
        } while (size > 0);
      }

      sResult = "OK";
    }
  }
  catch (WebException wexp)
  {
    if (wexp.Response != null)
    {
      HttpWebResponse response = (HttpWebResponse)wexp.Response;
      // 這裡可以取得 404 之類無法取得 Server Response 的 HttpStatusCode
      HttpStatusCode status = response.StatusCode;
      sResult = status.ToString();
    }
    sResult += wexp.Message.ToString();

  }
  catch (Exception ex)
  {
    sResult = "Error" + ex.Message.ToString();
  }
  return sResult;
}

沒有留言:

張貼留言

技術提供:Blogger.