C#学习教程:如何使用HttpWebRequest和HttpWebResponse类(Cookie、凭据等)下载文件当我通过传递用户名和密码等凭据请求URL时。我在响应中返回会话ID。获取该会话ID后如何进一步移动。使用凭据/cookie来跟踪经过身份验证的用户。我正在下载文件的确切URL和凭据。如果你想使用cookie,我会的。我需要读取文件数据并将其写入/保存在指定位置。我使用的代码是;字符串用户名=“”;字符串密码=“”;stringreqString="http://sofzh.miximages.com/c%23/uf.Length;intbytesRead=0;while(bytesToRead0){intn=str.Read(inBuf,bytesRead,bytesToRead);if(n==0)break;bytesRead+=n;bytesToRead-=n;}FileStreamfstr=newFileStream(weather.jpg",FileMode.OpenOrCreate,FileAccess.Write);fstr.Write(inBuf,0,bytesRead);海峡关闭();fstr.关闭();我这样做了:conststringbaseurl="http://www.some......thing.com/";Cookie容器cookie;第一种方法登录到Web服务器并获取会话ID:publicMethod1(stringuser,stringpassword){HttpWebRequestreq=(HttpWebRequest)WebRequest.Create(baseurl);要求。方法=“发布”;req.ContentType="application/x-www-form-urlencoded";stringlogin=string.Format("go=&Fuser={0}&Fpass={1}",用户,密码);byte[]postbuf=Encoding.ASCII.GetBytes(登录);req.ContentLength=postbuf.Length;流rs=req.GetRequestStream();rs.Write(postbuf,0,postbuf.Length);rs.关闭();cookie=req.CookieContainer=newCookieContainer();WebResponseresp=req.GetResponse();分别关闭();另一种从服务器获取文件的方法:stringGetPage(stringpath){HttpWebRequestreq=(HttpWebRequest)WebRequest.Create(path);req.CookieContainer=cookie;WebResponseresp=req.GetResponse();stringt=newStreamReader(resp.GetResponseStream(),Encoding.Default).ReadToEnd();返回IsoToWin1250(t);请注意,我将页面作为字符串返回。您最好将其作为bytes[]保存到磁盘。如果您的jpeg文件很小(通常不到GB),您可以简单地将它们放入内存流并保存到磁盘。在C#中大约需要2或3行简单的代码,而不是30行具有潜在危险内存泄漏的暴力代码,如上面提供的那样。以上为C#学习教程:如何使用HttpWebRequest和HttpWebResponse类(Cookies、credentials等),不代表立场,如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处:
