How to use HttpWebRequest to upload a file

Trying to load a file into code.

Current 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() 

Run this code and verify the response. ResponseUri indicates that it is redirected back to the login page, and not to the pdf file.

For some reason, it does not allow access to what I can skip since I am sending the username and password to uri? Thanks for your help.

+6
source share
3 answers

You do not need all this code to download a file from the network, just use the WebClient class and its DownloadFile method

+4
source

you should check and see if the site requires cookies (most of them), I would use a packet analyzer and run your code and see for sure what the server returns. use a violinist or http analyzer to register packages

0
source

With UWP, this has become a more pressing issue since UWP does not have a WebClient . The correct answer to this question is if you are redirected to the login page, then there should be a problem with your credentials or the installation header (or absence) for HttpWebRequest .

According to Microsoft , a download request is sent with a GetResponse() call to HttpWebRequest , so the downloaded file MUST be in the stream in the response (returned by the GetResponse() call mentioned above).

0
source

Source: https://habr.com/ru/post/893281/


All Articles