I have made a function to create a webrequest and load a api on my website to connect to ssh with parameters.
This is the function code:
Public Function sshExec(ByVal command As String)
Try
Dim request As WebRequest = _
WebRequest.Create("http://api.***.be/ssh.php?host=" + ComboBox1.Text + "&username=root&password=" + TextBox1.Text + "&command=" + command)
' Get the response.
Dim response As WebResponse = request.GetResponse()
' Get the stream containing content returned by the server.
Dim dataStream As Stream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
If responseFromServer.Contains("Login Failed") Then
lblStatus.Text = "Login failed"
lblStatus.ForeColor = Color.Red
Else
lblStatus.ForeColor = Color.Green
lblStatus.Text = "Connected"
End If
TextBox2.Text = "http://api.***.be/ssh.php?host=" + ComboBox1.Text + "&username=root&password=" + TextBox1.Text + "&command=" + command
' Clean up the streams and the response.
reader.Close()
response.Close()
Return responseFromServer
Catch ex As Exception
End Try
End Function
I made a textbox and when I use the function it puts the api link that it loads in a textbox. If I copy this and load it in my browser it works fine but with the webrequest it says:
Notice: Cannot connect to 62.113.*** Error 0. php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/niel/public_html/api/Net/SSH2.php on line 831
Login Failed
Also, when I use the function a second time it doesn't load the page at all.
Anyone know what's wrong? Thanks in advance :)
Most probably because you do not dispose the response, so simply call
response.Dispose()
after you closed it.
Related
I'm making a web request that completes successfully most of the time (target$ is a URL). But occasionally my code throws a valid exception, 404 not found, if the URL target$ doesn't exist, and execution stops. The code:
Sub scrape(target$)
Dim request As WebRequest = WebRequest.Create(target$)
Dim response As WebResponse = request.GetResponse()
Dim dataStream As Stream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
txtResponse.Text = ""
txtResponse.Text = responseFromServer
' Clean up the streams and the response.
reader.Close()
response.Close()
end sub
The exception, if thrown, happens in the second line, "Dim response...". So I tried adding a "try-catch" as shown.
Sub scrape(target$)
Dim request As WebRequest = WebRequest.Create(target$)
Dim response As WebResponse = request.GetResponse()
Try
Dim dataStream As Stream = response.GetResponseStream()
Catch
exflag = True
End Try
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
txtResponse.Text = ""
txtResponse.Text = responseFromServer
' Clean up the streams and the response.
reader.Close()
response.Close()
end sub
But now when I try to compile the code, VisualStudio tells me that "datastream is not declared" and the compile fails.
What am I doing wrong and how do I catch the exception when it's thrown?
Thanks...
A while ago I wrote a programme in VB.NET to use the Betfair Exchange API. It has worked perfectly for months, but overnight on Tuesday it stopped working. I can still log in, but from Wednesday I have been unable to get anything else from the server.
Betfair are investigating, but according to them nobody else seems to be experiencing the same problem - although I'm not sure how many will be using VB.NET.
Below is the function I have been using to obtain data from the API. Like I said it was working on Tuesday night but not from Wednesday morning. Is there anything here which is "not perfect" or "could be better", or perhaps there is some alternative code I could try? Or is there something which might have happened on my pc which has caused the problem?
The programme falls over at the line "dataStream = request.GetRequestStream() ". The error is "Received an unexpected EOF or 0 bytes from the transport stream."
I would be grateful for any advice that anyone could offer. Thank you!
Public Function CreateRequest(ByVal postData As String, Optional ByVal accountsApi As Boolean = False)
Dim Url As String = "https://api.betfair.com/exchange/betting/json-rpc/v1"
If accountsApi Then Url = "https://api.betfair.com/exchange/account/json-rpc/v1"
Dim request As WebRequest = Nothing
Dim dataStream As Stream = Nothing
Dim response As WebResponse = Nothing
Dim strResponseStatus As String = ""
Dim reader As StreamReader = Nothing
Dim responseFromServer As String = ""
Try
request = WebRequest.Create(New Uri(Url))
request.Method = "POST"
request.ContentType = "application/json-rpc"
request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8")
request.Headers.Add("X-Application", appKey)
request.Headers.Add("X-Authentication", sessToken)
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData) ' Data to post such as ListEvents, ListMarketCatalogue etc
request.ContentLength = byteArray.Length ' Set the ContentLength property of the WebRequest.
dataStream = request.GetRequestStream() ' Get the request stream.
dataStream.Write(byteArray, 0, byteArray.Length) ' Write the data to the request stream.
dataStream.Close() ' Close the Stream object.
response = request.GetResponse() ' Get the response.
strResponseStatus = CType(response, HttpWebResponse).StatusDescription ' Display the status below if required
dataStream = response.GetResponseStream() ' Get the stream containing content returned by the server.
reader = New StreamReader(dataStream) ' Open the stream using a StreamReader for easy access.
responseFromServer = reader.ReadToEnd() ' Read the content.
reader.Close() : dataStream.Close() : response.Close()
Catch ex As Exception
MsgBox("CreateRequest Error" & vbCrLf & ex.Message, MsgBoxStyle.Critical, " Error")
End Try
Return responseFromServer
End Function
I would check that the provider hasn't recently deprecated use of TLS 1.0 (as they should have done before now, in fact).
If so, your code needs to enforce use of TLS 1.1+:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
This only has to be set once, usually in the (static) type initializer or similar.
And I 100% agree with Andrew Mortimer that you should use Using blocks wherever possible. I'd also suggest moving all of your string values into variables or constants to clean things up and keep them maintainable. Eg:
Const ContentType As String = "application/json-rpc"
...
request.ContentType = ContentType
UPDATE
I just found this announcement on their site:
https://forum.developer.betfair.com/forum/developer-program/announcements/33563-tls-1-0-no-longer-supported-from-1st-december-all-betfair-api-endpoints
If you are allowed to use external dependencies within this project I would recommend using RestSharp nuget package it works really well for creating API requests and getting there response without having to use httpclient which gets messy.
Link: https://restsharp.dev/
So i have written code to allow me to download files from an FTP server using the system.io.stream function in vb.net. Now I need to be able to find the length of the stream, when i has finished.
I have worked with streamreader in the past but this stream doesn't work in the same way so i'm not sure how to proceed.
Try
Dim request As System.Net.FtpWebRequest
request = DirectCast(System.Net.WebRequest.Create("ftp://ftp.server.com/Folder/" & FileName & ".pdf"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("Username", "Password")
request.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
Dim stream As System.IO.Stream = request.GetResponse.GetResponseStream
'Dim OutPutFilepath As String = "DownloadTest" & "\" & IO.Path.GetFileName("ftp://ftp.Server.com/Folder/")
output = System.IO.File.Create("C:\Users\ASUS\Documents\TestFile2.pdf")
output.Close()
stream.Close()
Console.WriteLine("Downloaded")
Console.ReadLine()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Also, I have tried using the stream.length feature however, i got an exception saying something along the lines of "this stream does not support seek functions".
Thanks in advance
When using the following code, if I specify a wrong username/password combination I get a 407 error.
If I use a correct one, I get the page requested.
If I try again with a wrong username/password I get a normal response.
For some reason, WebRequest caches the proxy's username/password (CredentialCache) combination for the requested URL. If I change the URL pointing to a different domain, I get a proper 407.
How can I stop WebRequest from using last successful credential?
Dim request As WebRequest = WebRequest.Create("http://contoso.com")
request.Proxy = New WebProxy("http://myproxy:8080")
Dim username = InputBox("Username")
Dim password = InputBox("Password")
request.Proxy.Credentials = New NetworkCredential(username, password)
Try
Using response = request.GetResponse()
' Display the status.
txt_response.Text = CType(response, HttpWebResponse).StatusDescription & "Response is from cache?: " & response.IsFromCache
' Get the stream containing content returned by the server.
Dim dataStream As Stream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Display the content.
txt_Result.Text = responseFromServer
' Clean up the streams and the response.
reader.Close()
response.Close()
End Using
Catch ex As WebException
txt_response.Text = ex.Status & ": " & ex.Message
End Try
Can anybody tell me why the function below always returns true, even if the FTP directory in question does not exist?
The value of directoryURL which I pass in is of the form:
ftp://ip_address/directory/subdirectory/
and has a trailing forward slash.
Public Function DoesDirectoryExist(directoryUrl As String) As Boolean
' Check that the target URL is properly formatted
If Not directoryUrl.StartsWith("ftp://") Then directoryUrl = "ftp://" & directoryUrl
' Create a web request
Dim request As FtpWebRequest = DirectCast(WebRequest.Create(directoryUrl), FtpWebRequest)
request.Credentials = New NetworkCredential(_userName, _password)
request.Method = WebRequestMethods.Ftp.ListDirectory
' Try and list the contents of the directory
Try
Using response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
' We have been succesful so the directory exists
Return True
End Using
Catch ex As WebException
Dim response As FtpWebResponse = DirectCast(ex.Response, FtpWebResponse)
If response.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then
Return False
Else
Throw New ApplicationException("Unable to determine if FTP directory exists.")
End If
End Try
End Function
Weird. This works for me (I don't cast the request but I guess that shouldn't matter). This is the code I usually rely on:
Dim response As FtpWebResponse = request.GetResponse()
Using (response)
found = True
End Using
The alternative you have is reading the list of directories:
Using sr As New System.IO.StreamReader(response.GetResponseStream())
Using sw As New System.IO.StreamWriter("tempfile", False)
sw.Write(sr.ReadToEnd())
End Using
End Using
In the worst scenario, it should help you to tackle the problem (e.g., it always founds a directory called "ghost", which you might use to trigger the not-found).
Method 1
Public Function DirectoryExists(directory As String) As Boolean
Dim directoryExists__1 As Boolean
Dim request = DirectCast(WebRequest.Create(directory), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.ListDirectory
request.Credentials = New NetworkCredential("user", "pass")
Try
Using request.GetResponse()
directoryExists__1 = True
End Using
Catch generatedExceptionName As WebException
directoryExists__1 = False
End Try
Return directoryExists__1
End Function
Method 2
If Not DirectoryExists("ftp://" + FTPSettings.IP + "/" + lo_ScreenShotPath) Then
reqFTP = DirectCast(FtpWebRequest.Create(New Uri("ftp://" + FTPSettings.IP + "/" + lo_ScreenShotPath)), FtpWebRequest)
End If
i hope may i help this...