How do I know the encoding of a webpage that I read in with vb.net? - vb.net

I tried reading a webpage into my program using vb.net's HttpWebRequest. My problem has to do with figuring out the encoding of the web page before I actually read it into a string. When I read it in, some characters appear as diamonds with question-marks inside the diamonds. The web page itself looks fine in a browser, its just when I read it in that some characters aren't encoded right.
The original code I used was:
Dim myWebRequest As HttpWebRequest = WebRequest.Create(ourUri)
Dim myWebResponse As httpWebResponse = myWebRequest.GetResponse()
Then to try to get the encoding. I used:
Dim contentType As String = myWebResponse.ContentType
Dim charset As String = myWebResponse.CharacterSet
But both 'contentType' and 'charset' end up with the value 'text/html'. What I want to know is if the webpage is encoded in 'utf-8' or some other character set, so I can later retrieve it like this:
Dim receiveStream As Stream = myWebResponse.GetResponseStream()
Dim encode As Encoding = System.Text.Encoding.GetEncoding(charset)
Using reader As StreamReader = New StreamReader(receiveStream, encode)
So to sum up, there seems to be no way to inquire what the encoding is, and then use the answer to read the webpage the right way.
Is that true? Any help is appreciated.
The entire code of the routine (asked for by a commenter) follows:
Public Shared Function DownloadFileUsingURL(ByVal URLstring As String, ByVal descFilePathAndName As String, ByRef errorMessage As String, ByRef hadRedirect As Boolean,
ByRef newURL As String, ByRef isSecureConnection As Boolean, ByVal didSupplyfullfilename As Boolean, ByRef downloadedcontent As String,
ByRef httpTohttps As Boolean, ByRef httpsTohttp As Boolean, ByRef BytesRead As Integer) As Boolean
Dim ourUri As New Uri(URLstring)
Dim csh As New ClassSyncHttp
Dim expectSecureConnection As Boolean
Dim domainchanged As Boolean
newURL = ""
errorMessage = ""
hadRedirect = False
httpTohttps = False
httpsTohttp = False
isSecureConnection = False
If URLstring.ToLower.StartsWith("https:") Then
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault
expectSecureConnection = True
Else
ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault
expectSecureConnection = False
End If
Try
Dim myWebRequest As HttpWebRequest = WebRequest.Create(ourUri) ' I changed webrequest to httpwebrequest
Dim cookieContainer As CookieContainer = New CookieContainer ' needs httpwebrequest to work
myWebRequest.CookieContainer = cookieContainer
myWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials
myWebRequest.UserAgent = "BrowseNet"
myWebRequest.Timeout = ClassGlobalVariables.downloadTimeoutMilliseconds
myWebRequest.Credentials = CredentialCache.DefaultCredentials
Dim myWebResponse As HttpWebResponse = myWebRequest.GetResponse()
Dim contentType As String = myWebResponse.ContentType
Dim charset As String = myWebResponse.CharacterSet
If Not ourUri.Equals(myWebResponse.ResponseUri) Then
newURL = myWebResponse.ResponseUri.ToString
hadRedirect = True
If newURL.ToLower.StartsWith("https") Then
isSecureConnection = True
End If
compareURLs(URLstring, newURL, httpTohttps, domainchanged)
End If
Dim receiveStream As Stream = myWebResponse.GetResponseStream()
If didSupplyfullfilename Then
Using fs As FileStream = File.Create(descFilePathAndName)
receiveStream.CopyTo(fs)
BytesRead = fs.Length
End Using
Else
Dim encode As Encoding = System.Text.Encoding.GetEncoding(charset)
Using reader As StreamReader = New StreamReader(receiveStream, encode)
' receiveStream.Seek(0, SeekOrigin.Begin)
downloadedcontent = reader.ReadToEnd()
BytesRead = downloadedcontent.Length
End Using
End If
myWebResponse.Close()
If expectSecureConnection Then
isSecureConnection = True
Else
isSecureConnection = False
End If
Return True
Catch ex As webException
If expectSecureConnection Then
' guessing here that the problem was that was wrong about secure connection. (Problem could be elsewhere, of course)
isSecureConnection = False
httpsTohttp = True
If ex.HResult = System.Net.WebExceptionStatus.SecureChannelFailure Then
' not sure what to do
End If
'Else
' isSecureConnection = True
End If
errorMessage = ex.Message
Return False
End Try
End Function

Related

VB.NET posting with custom headers

heya I'm required to post a json string to the server but I keep getting the error
The underlying connection was closed: An unexpected error occurred on a send.
I've tried adding these two codes after researching but still got the same error, any ideas?
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
this is my full code, thePostData is a JsonConvert.SerializeObject(Dictionary) String
Public Function PostToServer(thePostData As String, theConcatted As String, theNonce As String, theTimeStamp As String, theUri as Uri)
Try
'ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
Dim theRequest As HttpWebRequest = HttpWebRequest.Create(theUri)
Dim theByteArray As Byte() = Encoding.UTF8.GetBytes(thePostData)
theRequest.Method = "POST"
theRequest.ContentType = "application/json"
theRequest.Headers.Add("X-Authentication-Version", "1.1")
theRequest.Headers.Add("X-Authentication-Method", "SHA256WithRSA")
theRequest.Headers.Add("X-Authentication-KeyId", theKeyId)
theRequest.Headers.Add("X-Authentication-Nonce", theNonce)
theRequest.Headers.Add("X-Authentication-Timestamp", theTimeStamp)
theRequest.Headers.Add("X-Authentication-Sign", getDataSignature(theConcatted))
theRequest.ContentLength = theByteArray.Length
Dim theDataStream As Stream = theRequest.GetRequestStream()
theDataStream.Write(theByteArray, 0, theByteArray.Length)
theDataStream.Close()
Return True
Catch ex As Exception
Console.WriteLine(ex.Message)
Return False
End Try
End Function
Function getDataSignature(theData As String)
Dim theRSA As New RSACryptoServiceProvider
theRSA.FromXmlString(thePrivateKey)
Dim theRSAFormatter As New RSAPKCS1SignatureFormatter(theRSA)
theRSAFormatter.SetHashAlgorithm("SHA256")
Dim theSHhash As New SHA256Managed()
Dim theSignedHashValue As Byte() = theRSAFormatter.CreateSignature(theSHhash.ComputeHash(New UnicodeEncoding().GetBytes(theData)))
Dim theStringBuilder As New StringBuilder(theSignedHashValue.Length * 2)
For Each b As Byte In theSignedHashValue
theStringBuilder.Append(Conversion.Hex(b))
Next
Return theStringBuilder.ToString().ToLower()
End Function

Docusign download file from template which get illegal characters in file base64string format using Chilkat and rest api

I can get file from template which passing templateid and documentid, when retrun from api , i will get as base64string format, and when i try to convert as byte,
I get an error "Additional information: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."
Here the code which i used to download file from template
Dim rest As New Chilkat.Rest
Dim success As Boolean
Dim bTls As Boolean = True
Dim port As Integer = 443
Dim bAutoReconnect As Boolean = True
success = rest.Connect("demo.docusign.net", port, bTls, bAutoReconnect)
If (success <> True) Then
Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
Debug.WriteLine(rest.LastErrorText)
Exit Sub
End If
rest.AddHeader("X-DocuSign-Authentication", "{ ""Username"": ""DocuSign#example.com"", ""Password"":""DocuSign_password"", ""IntegratorKey"":""DocuSign_Integrator_Key"" }")
Dim sbResponseBody As New Chilkat.StringBuilder
success = rest.FullRequestNoBodySb("GET", "/restapi/v2.1/accounts/xxxx/templates/xxxx-xxxx-xxxx-xxxx-xxxx/documents/x", sbResponseBody)
If (success <> True) Then
Debug.WriteLine(rest.LastErrorText)
Exit Sub
End If
Dim respStatusCode As Integer = rest.ResponseStatusCode
If (respStatusCode >= 400) Then
Debug.WriteLine("Response Status Code = " & respStatusCode)
Debug.WriteLine("Response Header:")
Debug.WriteLine(rest.ResponseHeader)
Debug.WriteLine("Response Body:")
Debug.WriteLine(sbResponseBody.GetAsString())
Exit Sub
End If
Dim jsonResponse As New Chilkat.JsonObject
jsonResponse.LoadSb(sbResponseBody)
Dim pdfBytes As Byte() = Convert.FromBase64String(sbResponseBody.ToString)
Regards,
Aravind
i changed my code from chilkat dll to Docusing dll 3.0.0 , using docusing dll i can download file from envelope, here i past my code , it will useful to some other developer.I am used .net framework code download file from file stream.
Private Function DoWnload(ByVal accessToken As String, ByVal basePath As String, ByVal accountId As String, ByVal envelopeId As String, ByVal documents As List(Of EnvelopeDocItem), ByVal docSelect As String) As String
Dim config = New Configuration(New ApiClient(basePath))
config.AddDefaultHeader("Authorization", "Bearer " & accessToken)
Dim envelopesApi As EnvelopesApi = New EnvelopesApi(config)
Dim results As System.IO.Stream = envelopesApi.GetDocument(accountId, envelopeId, docSelect)
Dim docItem As EnvelopeDocItem = documents.FirstOrDefault(Function(d) docSelect.Equals(d.DocumentId))
Dim docName As String = docItem.Name
Dim hasPDFsuffix As Boolean = docName.ToUpper().EndsWith(".PDF")
Dim pdfFile As Boolean = hasPDFsuffix
Dim docType As String = docItem.Type
If ("content".Equals(docType) OrElse "summary".Equals(docType)) AndAlso Not hasPDFsuffix Then
docName += ".pdf"
pdfFile = True
End If
If "zip".Equals(docType) Then
docName += ".zip"
End If
Dim mimetype As String
If pdfFile Then
mimetype = "application/pdf"
ElseIf "zip".Equals(docType) Then
mimetype = "application/zip"
Else
mimetype = "application/octet-stream"
End If
Dim bytesRead As Integer
Dim buffer(4096) As Byte
Using outFile As New System.IO.FileStream("C:\File.pdf", IO.FileMode.Create, IO.FileAccess.Write)
Do
bytesRead = results.Read(buffer, 0, buffer.Length)
If bytesRead > 0 Then
outFile.Write(buffer, 0, bytesRead)
End If
Loop While bytesRead > 0
End Using
Return ""
End Function
Dim envelopeDocItems As List(Of EnvelopeDocItem) = New List(Of EnvelopeDocItem) From {
New EnvelopeDocItem With {
.Name = "Combined",
.Type = "content",
.DocumentId = "combined"
},
New EnvelopeDocItem With {
.Name = "Zip archive",
.Type = "zip",
.DocumentId = "archive"
}
Thanks to Inbar Gazit...
Thanks and Regards,
Aravind
Here is an example: https://www.example-code.com/vbnet/docusign_download_envelope_document.asp
Also see the other VB.NET DocuSign examples: https://www.example-code.com/vbnet/docusign.asp

How to download files from Docusign api using vb.net

How to download files once signed by all using vb.net. I manged to send envelope with template id.So i want to get back that file using envelope id, pls provide some sampe code to retrieve back files using vb.net.
Here code what i used in vb.net
Private Function DoWnload(ByVal accessToken As String, ByVal basePath As String, ByVal accountId As String, ByVal envelopeId As String, ByVal documents As List(Of EnvelopeDocItem), ByVal docSelect As String) As String
Dim config = New Configuration(New ApiClient(basePath))
config.AddDefaultHeader("Authorization", "Bearer " & accessToken)
Dim envelopesApi As EnvelopesApi = New EnvelopesApi(config)
Dim results As System.IO.Stream = envelopesApi.GetDocument(accountId, envelopeId, docSelect)
Dim docItem As EnvelopeDocItem = documents.FirstOrDefault(Function(d) docSelect.Equals(d.DocumentId))
Dim docName As String = docItem.Name
Dim hasPDFsuffix As Boolean = docName.ToUpper().EndsWith(".PDF")
Dim pdfFile As Boolean = hasPDFsuffix
Dim docType As String = docItem.Type
If ("content".Equals(docType) OrElse "summary".Equals(docType)) AndAlso Not hasPDFsuffix Then
docName += ".pdf"
pdfFile = True
End If
If "zip".Equals(docType) Then
docName += ".zip"
End If
Dim mimetype As String
If pdfFile Then
mimetype = "application/pdf"
ElseIf "zip".Equals(docType) Then
mimetype = "application/zip"
Else
mimetype = "application/octet-stream"
End If
''Dim f1 As FileStream = New FileStream("sample.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
' Return File(results, mimetype, docName)
Dim bytesRead As Integer
Dim buffer(4096) As Byte
Using outFile As New System.IO.FileStream("C:\File.pdf", IO.FileMode.Create, IO.FileAccess.Write)
Do
bytesRead = results.Read(buffer, 0, buffer.Length)
If bytesRead > 0 Then
outFile.Write(buffer, 0, bytesRead)
End If
Loop While bytesRead > 0
End Using
Return ""
End Function
Dim envelopeDocItems As List(Of EnvelopeDocItem) = New List(Of EnvelopeDocItem) From {
New EnvelopeDocItem With {
.Name = "Combined",
.Type = "content",
.DocumentId = "combined"
},
New EnvelopeDocItem With {
.Name = "Zip archive",
.Type = "zip",
.DocumentId = "archive"
}
in that docSelect what need to pass ? i passed documetid, getting error.
Regards,
Aravind
Private Function DoWork(ByVal accessToken As String, ByVal basePath As String, ByVal accountId As String, ByVal envelopeId As String, ByVal documents As List(Of EnvelopeDocItem), ByVal docSelect As String) As FileStreamResult
Dim config = New Configuration(New ApiClient(basePath))
config.AddDefaultHeader("Authorization", "Bearer " & accessToken)
Dim envelopesApi As EnvelopesApi = New EnvelopesApi(config)
Dim results As System.IO.Stream = envelopesApi.GetDocument(accountId, envelopeId, docSelect)
Dim docItem As EnvelopeDocItem = documents.FirstOrDefault(Function(d) docSelect.Equals(d.DocumentId))
Dim docName As String = docItem.Name
Dim hasPDFsuffix As Boolean = docName.ToUpper().EndsWith(".PDF")
Dim pdfFile As Boolean = hasPDFsuffix
Dim docType As String = docItem.Type
If ("content".Equals(docType) OrElse "summary".Equals(docType)) AndAlso Not hasPDFsuffix Then
docName += ".pdf"
pdfFile = True
End If
If "zip".Equals(docType) Then
docName += ".zip"
End If
Dim mimetype As String
If pdfFile Then
mimetype = "application/pdf"
ElseIf "zip".Equals(docType) Then
mimetype = "application/zip"
Else
mimetype = "application/octet-stream"
End If
Return File(results, mimetype, docName)
End Function
You will need to get the nuget from here - https://www.nuget.org/packages/DocuSign.eSign.dll/ but version 5.0.0 won't work with the code above, use version 4.3
Update: adding this additional class:
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Threading.Tasks
Namespace Models
Public Class EnvelopeDocItem
Public Property Name As String
Public Property Type As String
Public Property DocumentId As String
End Class
End Namespace

VB.net synchronisation Folder and file [duplicate]

I am trying to download multiple directories from FTP server to my local machine,
I have tried this,
Const localFile As String = "C:\Documents and Settings\cr\Desktop\T\New Folder\"
Const remoteFile As String = "textbox.Text"
Const host As String = "ftp://ftp.example.com"
Const username As String = "username"
Const password As String = "password"
For i1 = 0 To ListBox1.SelectedItems.Count - 1
Dim li As New ListViewItem
li = ListView1.Items.Add(ListBox1.SelectedItems(i1))
Dim URI1 As String = host + remoteFile & "/" & ListBox1.SelectedItems(i1)
Dim ftp1 As System.Net.FtpWebRequest = CType(FtpWebRequest.Create(URI1), FtpWebRequest)
ftp1.Credentials = New System.Net.NetworkCredential(username, password)
ftp1.KeepAlive = False
ftp1.UseBinary = True
ftp1.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
Using response As System.Net.FtpWebResponse = CType(ftp1.GetResponse, System.Net.FtpWebResponse)
Using responseStream As IO.Stream = response.GetResponseStream
Dim length As Integer = response.ContentLength
Dim bytes(length) As Byte
'loop to read & write to file
Using fs As New IO.FileStream(localFile & ListBox1.SelectedItems(i1), IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 1
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0 'see Note(1)
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
End Using
li.BackColor = Color.Aquamarine
Next
But here the problem is that I am able to download multiple files from folders, but unable to download the sub directories and their contents from the main directory.
Basically the main directory consist of files and sub directories both. So is there any possible way to download sub directory and its contents from FTP?
Thanks in advance.
Translating my answer to C# Download all files and subdirectories through FTP to VB.NET:
The FtpWebRequest does not have any explicit support for recursive file download (or any other recursive operation). You have to implement the recursion yourself:
List the remote directory
Iterate the entries, downloading files and recursing into subdirectories (listing them again, etc.)
A tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the FtpWebRequest. The FtpWebRequest unfortunately does not support the MLSD command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.
Your options are:
Do an operation on a file name that is certain to fail for file and succeeds for directories (or vice versa). I.e. you can try to download the "name". If that succeeds, it's a file, if that fails, it's a directory.
You may be lucky and in your specific case, you can tell a file from a directory by a file name (i.e. all your files have an extension, while subdirectories do not)
You use a long directory listing (LIST command = ListDirectoryDetails method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by the d at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)
Sub DownloadFtpDirectory(
url As String, credentials As NetworkCredential, localPath As String)
Dim listRequest As FtpWebRequest = WebRequest.Create(url)
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails
listRequest.Credentials = credentials
Dim lines As List(Of String) = New List(Of String)
Using listResponse As FtpWebResponse = listRequest.GetResponse(),
listStream As Stream = listResponse.GetResponseStream(),
listReader As StreamReader = New StreamReader(listStream)
While Not listReader.EndOfStream
lines.Add(listReader.ReadLine())
End While
End Using
For Each line As String In lines
Dim tokens As String() =
line.Split(New Char() {" "}, 9, StringSplitOptions.RemoveEmptyEntries)
Dim name As String = tokens(8)
Dim permissions As String = tokens(0)
Dim localFilePath As String = Path.Combine(localPath, name)
Dim fileUrl As String = url + name
If permissions(0) = "d" Then
If Not Directory.Exists(localFilePath) Then
Directory.CreateDirectory(localFilePath)
End If
DownloadFtpDirectory(fileUrl + "/", credentials, localFilePath)
Else
Dim downloadRequest As FtpWebRequest = WebRequest.Create(fileUrl)
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile
downloadRequest.Credentials = credentials
Using downloadResponse As FtpWebResponse = downloadRequest.GetResponse(),
sourceStream As Stream = downloadResponse.GetResponseStream(),
targetStream As Stream = File.Create(localFilePath)
Dim buffer As Byte() = New Byte(10240 - 1) {}
Dim read As Integer
Do
read = sourceStream.Read(buffer, 0, buffer.Length)
If read > 0 Then
targetStream.Write(buffer, 0, read)
End If
Loop While read > 0
End Using
End If
Next
End Sub
Use the function like:
Dim credentials As NetworkCredential = New NetworkCredential("user", "mypassword")
Dim url As String = "ftp://ftp.example.com/directory/to/download/"
DownloadFtpDirectory(url, credentials, "C:\target\directory")
If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the MLSD command and/or parsing various LIST listing formats; and recursive downloads.
For example with WinSCP .NET assembly you can download whole directory with a single call to the Session.GetFiles:
' Setup session options
Dim SessionOptions As SessionOptions = New SessionOptions
With SessionOptions
.Protocol = Protocol.Ftp
.HostName = "ftp.example.com"
.UserName = "user"
.Password = "mypassword"
End With
Using session As Session = New Session()
' Connect
session.Open(SessionOptions)
' Download files
session.GetFiles("/directory/to/download/*", "C:\target\directory\*").Check()
End Using
Internally, WinSCP uses the MLSD command, if supported by the server. If not, it uses the LIST command and supports dozens of different listing formats.
The Session.GetFiles method is recursive by default.
(I'm the author of WinSCP)
Check out my FTP class: Its pretty straight forward.
Take a look at my FTP class, it might be exactly what you need.
Public Class FTP
'-------------------------[BroCode]--------------------------
'----------------------------FTP-----------------------------
Private _credentials As System.Net.NetworkCredential
Sub New(ByVal _FTPUser As String, ByVal _FTPPass As String)
setCredentials(_FTPUser, _FTPPass)
End Sub
Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String)
Dim _FileInfo As New System.IO.FileInfo(_FileName)
Dim _FtpWebRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(New Uri(_UploadPath)), System.Net.FtpWebRequest)
_FtpWebRequest.Credentials = _credentials
_FtpWebRequest.KeepAlive = False
_FtpWebRequest.Timeout = 20000
_FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
_FtpWebRequest.UseBinary = True
_FtpWebRequest.ContentLength = _FileInfo.Length
Dim buffLength As Integer = 2048
Dim buff(buffLength - 1) As Byte
Dim _FileStream As System.IO.FileStream = _FileInfo.OpenRead()
Try
Dim _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream()
Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength)
Do While contentLen <> 0
_Stream.Write(buff, 0, contentLen)
contentLen = _FileStream.Read(buff, 0, buffLength)
Loop
_Stream.Close()
_Stream.Dispose()
_FileStream.Close()
_FileStream.Dispose()
Catch ex As Exception
MessageBox.Show(ex.Message, "Upload Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Public Sub DownloadFile(ByVal _FileName As String, ByVal _ftpDownloadPath As String)
Try
Dim _request As System.Net.FtpWebRequest = System.Net.WebRequest.Create(_ftpDownloadPath)
_request.KeepAlive = False
_request.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
_request.Credentials = _credentials
Dim _response As System.Net.FtpWebResponse = _request.GetResponse()
Dim responseStream As System.IO.Stream = _response.GetResponseStream()
Dim fs As New System.IO.FileStream(_FileName, System.IO.FileMode.Create)
responseStream.CopyTo(fs)
responseStream.Close()
_response.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Download Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Public Function GetDirectory(ByVal _ftpPath As String) As List(Of String)
Dim ret As New List(Of String)
Try
Dim _request As System.Net.FtpWebRequest = System.Net.WebRequest.Create(_ftpPath)
_request.KeepAlive = False
_request.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails
_request.Credentials = _credentials
Dim _response As System.Net.FtpWebResponse = _request.GetResponse()
Dim responseStream As System.IO.Stream = _response.GetResponseStream()
Dim _reader As System.IO.StreamReader = New System.IO.StreamReader(responseStream)
Dim FileData As String = _reader.ReadToEnd
Dim Lines() As String = FileData.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
For Each l As String In Lines
ret.Add(l)
Next
_reader.Close()
_response.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Directory Fetch Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return ret
End Function
Private Sub setCredentials(ByVal _FTPUser As String, ByVal _FTPPass As String)
_credentials = New System.Net.NetworkCredential(_FTPUser, _FTPPass)
End Sub
End Class
To initialize:
Dim ftp As New FORM.FTP("username", "password")
ftp.UploadFile("c:\file.jpeg", "ftp://domain/file.jpeg")
ftp.DownloadFile("c:\file.jpeg", "ftp://ftp://domain/file.jpeg")
Dim directory As List(Of String) = ftp.GetDirectory("ftp://ftp.domain.net/")
ListBox1.Items.Clear()
For Each item As String In directory
ListBox1.Items.Add(item)
Next

call http get using proxy

How can I edit the code to accept proxy?
CallHttp functions
Public Shared Function CallHttp(ByVal url As String, _
ByVal params As String, _
ByVal httpPost As Boolean) As String
If httpPost Then
Return CallHttpPost(url, params)
Else
Return CallHttpGet(url, params)
End If
End Function
CallHttpPost function:
Protected Shared Function CallHttpPost(ByVal url As String, _
ByVal params As String) As String
Dim loHttp As HttpWebRequest
'params = QueryStringEncode(params, TypeEncodeEnum.urlEncode)
loHttp = CType(WebRequest.Create(url), HttpWebRequest)
loHttp.Method = "POST"
Dim requestWriter As StreamWriter = New StreamWriter(loHttp.GetRequestStream())
If Not String.IsNullOrEmpty(params) Then
requestWriter.Write(params)
End If
requestWriter.Close()
loHttp.ContentType = "application/x-www-form-urlencoded"
loHttp.Headers.Set("Pragma", "no-cache")
loHttp.AllowAutoRedirect = True
loHttp.KeepAlive = True
loHttp.Timeout = 30 * 1000
'loHttp.Referer = url
Dim loWebResponse As HttpWebResponse = CType(loHttp.GetResponse(), HttpWebResponse)
Dim enc As Encoding = System.Text.Encoding.UTF8
Dim loResponseStream As StreamReader = New StreamReader(loWebResponse.GetResponseStream(), enc)
Dim lcHtml As String = loResponseStream.ReadToEnd()
loWebResponse.Close()
loResponseStream.Close()
Return lcHtml
End Function
Im behind a corporate firewall and I get a 407 proxy authentication required error if I use the function like this
strXML = CallHttp(API_URL, sb.ToString, False)
any ideas?
user and pass are the authentication of your proxy
Dim myProxy As New WebProxy("192.168.1.2:8080")
Dim authentication As New System.Net.NetworkCredential("user", "pwd")
myProxy.Credentials = authentication
Dim loHttp As HttpWebRequest
loHttp .Proxy = myProxy