簡體   English   中英

如何使用HttpWebRequest和HttpWebResponse類(Cookies,憑據等)下載文件

[英]How to Download the File using HttpWebRequest and HttpWebResponse class(Cookies,Credentials,etc.)

謝謝icktoofay,我嘗試使用HttpWebRequestHttpWebResponse

當我通過傳遞憑據(如用戶名和密碼)來請求URL時。

我將在響應中返回會話ID。

獲得該會話ID后,如何進一步操作。

使用憑據/ cookie跟蹤經過身份驗證的用戶。 我要下載文件的確切網址和憑據。 如果您想使用Cookies,我會的。 我需要讀取文件數據並將其寫入/保存在指定位置。

我正在使用的代碼是;

string username = "";
string password = "";
string reqString = "https://xxxx.com?FileNAme=asfhasf.mro" + "?" + 
             "username=" + username + &password=" + password;
byte[] requestData = Encoding.UTF8.GetBytes(reqString);
string s1;
CookieContainer cc = new CookieContainer();

var request = (HttpWebRequest)WebRequest.Create(loginUri);
request.Proxy = null;
request.CookieContainer = cc;
request.Method = "POST";
HttpWebResponse ws = (HttpWebResponse)request.GetResponse();
Stream str = ws.GetResponseStream();
//ws.Cookies
//var request1 = (HttpWebRequest)WebRequest.Create(loginUri);
 byte[] inBuf = new byte[100000];
int bytesToRead = (int) inBuf.Length;
int bytesRead = 0;
while (bytesToRead > 0) 
{
    int n = str.Read(inBuf, bytesRead,bytesToRead);
    if (n==0)
    break;
    bytesRead += n;
    bytesToRead -= n;
}
FileStream fstr = new FileStream("weather.jpg", FileMode.OpenOrCreate, 
                                     FileAccess.Write);
fstr.Write(inBuf, 0, bytesRead);
str.Close();
fstr.Close();

這是我的方法:

const string baseurl = "http://www.some......thing.com/";
CookieContainer cookie;

第一種方法登錄到Web服務器並獲取會話ID:

public Method1(string user, string password) {
  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseurl);

  req.Method = "POST";
  req.ContentType = "application/x-www-form-urlencoded";
  string login = string.Format("go=&Fuser={0}&Fpass={1}", user, password);
  byte[] postbuf = Encoding.ASCII.GetBytes(login);
  req.ContentLength = postbuf.Length;
  Stream rs = req.GetRequestStream();
  rs.Write(postbuf,0,postbuf.Length);
  rs.Close();

  cookie = req.CookieContainer = new CookieContainer();

  WebResponse resp = req.GetResponse();
  resp.Close();
}

另一種方法是從服務器獲取文件:

string GetPage(string path) {
  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(path);
  req.CookieContainer = cookie;
  WebResponse resp = req.GetResponse();
  string t = new StreamReader(resp.GetResponseStream(), Encoding.Default).ReadToEnd();
  return IsoToWin1250(t);
}

請注意,我以字符串形式返回頁面。 您最好將其作為bytes []返回以保存到磁盤。 如果您的jpeg文件很小(通常大小不超過千兆字節),則只需將它們放入內存流,然后保存到磁盤即可。 在C#中將需要2到3條簡單的行,而不是像上面提供的那樣有可能造成潛在危險內存泄漏的30行艱難代碼。

public override DownloadItems GetItemStream(string itemID, object config = null, string downloadURL = null, string filePath = null, string)
    {
        DownloadItems downloadItems = new DownloadItems();
        try
        {
            if (!string.IsNullOrEmpty(filePath))
            {
                using (FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
                {
                    if (!string.IsNullOrEmpty(downloadURL))
                    {
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downloadURL);
                        request.Method = WebRequestMethods.Http.Get;
                        request.PreAuthenticate = true;
                        request.UseDefaultCredentials = true;
                        const int BUFFER_SIZE = 16 * 1024;
                        {
                            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                            {
                                using (var responseStream = response.GetResponseStream())
                                {
                                    var buffer = new byte[BUFFER_SIZE];
                                    int bytesRead;
                                    do
                                    {
                                        bytesRead = responseStream.Read(buffer, 0, BUFFER_SIZE);
                                        fileStream.Write(buffer, 0, bytesRead);
                                    } while (bytesRead > 0);
                                }
                            }
                            fileStream.Close();
                            downloadItems.IsSuccess = true;
                        }
                    }
                    else
                        downloadItems.IsSuccess = false;
                }
            }
        }
        catch (Exception ex)
        {
            downloadItems.IsSuccess = false;
            downloadItems.Exception = ex;
        }
        return downloadItems;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM