首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用HttpWebRequest和HttpWebResponse类下载文件(Cookie、凭证等)

如何使用HttpWebRequest和HttpWebResponse类下载文件(Cookie、凭证等)
EN

Stack Overflow用户
提问于 2011-01-15 21:57:35
回答 2查看 67.5K关注 0票数 17

谢谢,我试过使用HttpWebRequestHttpWebResponse

当我通过传递像UserName和密码这样的凭证来请求URL时。

我将在响应中取回会话Id。

在获得会话Id之后,如何进一步。

使用凭证/cookie跟踪经过身份验证的用户。我有确切的网址的文件要下载和凭证。如果你想使用Cookie,我会的。我需要读取File数据并将其写入/保存到指定位置。

我使用的代码是;

代码语言:javascript
复制
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();
EN

回答 2

Stack Overflow用户

发布于 2011-01-16 13:54:54

我是这样做的:

代码语言:javascript
复制
const string baseurl = "http://www.some......thing.com/";
CookieContainer cookie;

第一种方法登录到web服务器并获取会话id:

代码语言:javascript
复制
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();
}

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

代码语言:javascript
复制
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行代码。

票数 20
EN

Stack Overflow用户

发布于 2019-10-01 20:05:05

代码语言:javascript
复制
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;
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4699938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档