如何使用HttpWebRequest和HttpWebResponse类(Cookies,凭据等)下载文件

Vin*_*nay 17 c# winforms

谢谢icktoofay,我尝试使用HttpWebRequestHttpWebResponse.

当我通过传递诸如UserName和Password之类的凭证来请求URL时.

我将在响应中返回会话ID.

获得该会话ID后,如何进一步移动.

使用凭据/ cookie跟踪经过身份验证的用户.我正在下载文件的精确URL和凭据.如果你想使用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();
Run Code Online (Sandbox Code Playgroud)

Al *_*epp 20

我是这样做的:

const string baseurl = "http://www.some......thing.com/";
CookieContainer cookie;
Run Code Online (Sandbox Code Playgroud)

第一种方法登录到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();
}
Run Code Online (Sandbox Code Playgroud)

另一种方法从服务器获取文件:

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);
}
Run Code Online (Sandbox Code Playgroud)

请注意,我将页面作为字符串返回.您可能最好将其作为bytes []保存到磁盘.如果你的jpeg文件很小(它们通常不是千兆字节),你可以简单地将它们放到内存流中,然后保存到磁盘.在C#中需要大约2或3条简单的行,而不是像上面提到的那样有30行强硬的代码存在潜在的危险内存泄漏.