如何使用HttpWebRequest下载文件 [英] How to use HttpWebRequest to download file
本文介绍了如何使用HttpWebRequest下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试在代码中下载文件.
Trying to download file in code.
当前代码:
Dim uri As New UriBuilder
uri.UserName = "xxx"
uri.Password = "xxx"
uri.Host = "xxx"
uri.Path = "xxx.aspx?q=65"
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(uri.Uri), HttpWebRequest)
request.AllowAutoRedirect = True
request = DirectCast(WebRequest.Create(DownloadUrlIn), HttpWebRequest)
request.Timeout = 10000
'request.AllowWriteStreamBuffering = True
Dim response As HttpWebResponse = Nothing
response = DirectCast(request.GetResponse(), HttpWebResponse)
Dim s As Stream = response.GetResponseStream()
'Write to disk
Dim fs As New FileStream("c:xxx.pdf", FileMode.Create)
Dim read As Byte() = New Byte(255) {}
Dim count As Integer = s.Read(read, 0, read.Length)
While count > 0
fs.Write(read, 0, count)
count = s.Read(read, 0, read.Length)
End While
'Close everything
fs.Close()
s.Close()
response.Close()
运行此代码并检查 response.ResponseUri 表明我被重定向回登录页面而不是 pdf 文件.
Running this code and checking the response.ResponseUri indicates im being redirected back to the login page and not to the pdf file.
出于某种原因,它没有授权访问我在 uri 中发送用户名和密码时可能会遗漏什么?感谢您的帮助
For some reason its not authorising access what could I be missing as Im sending the user name and password in the uri? Thanks for your help
推荐答案
从网上下载文件不需要所有这些代码只需使用 WebClient 类及其 DownloadFile 方法
You don't need all of that code to download a file from the net just use the WebClient class and its DownloadFile method
这篇关于如何使用HttpWebRequest下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文