I am trying to write a console script that makes a POST request to a web server with post data and saves the response from the server to a file. The server response is a compressed tar archive. I'm able to make the request using weblclient upload data, but I cannot figure out a way to save the binary response to a variable and eventually to a file.
I am using vb.net framework 1.1.
Here is a snippet of my code so far:
' Download a single binary file from a server and save it to a local folder
Public Sub DownloadAndSaveFile(ByVal Url As String, ByVal Filename As String, ByVal User As String, ByVal Pass As String, ByVal Debug As Integer)
' The post data template
Dim PostdataTemplate As String = _
"handler=SOME_URLENCODED_D
ATA"
Dim PostdataArray As Byte() = Encoding.ASCII.GetBytes(Po
stdata)
' Create a new NetworkCredential object
Dim NetworkCredential As New NetworkCredential(User, Pass)
Try
' Create a new WebClient instance
Dim myWebClient As New WebClient
' Set Preauthenticate property to true
'myWebClient.PreAuthentica
te = True
' Associate the NetworkCrbedential object with the 'WebRequest' object
myWebClient.Credentials = NetworkCredential
' Add required HTTP headers to request
myWebClient.Headers.Add("A
ccept", "*/*")
myWebClient.Headers.Add("C
ontent-Typ
e", "application/x-www-form-ur
lencoded")
' UploadData method implicitly sets HTTP POST as the request method
Dim responseArray As Byte() = myWebClient.UploadData(Url
, PostdataArray)
' The response array as byte generates an exception!
Catch Ex As Exception
WriteLine("Error: " & Ex.Message)
End Try
End Sub
I get an exception when saving the response as a byte:
Error: The underlying connection was closed: The server committed an HTTP protocol violation.
If I change the server to respond with ascii text, the response is correctly saved. I think the issue is that I'm trying to save binary data to a variable that only handles text.
Can someone provide an example of how to send a POST request with parameters and then save the binary file that the server responds with to a local file?
Thanks!
Start Free Trial