HTTP response code checker in VB? - vb.net

i'm a new in VB and i'm trying to make a program that
gets and displays the HTTP response code of a website.
something like:
http response code of target website www.example.com : 200 OK
etc.
I Tried to code it myself but i couldn't , And i also tried to find online but i didn't
found something that works.
i found this http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.statuscode(v=vs.110).aspx
i tried that and that didn't really helped me.
Anyone has a code that does that?

I'm a C# guy, so this might not be perfect, but I believe this should do it.
Public Shared Function GetResponse(uri As String) As HttpStatusCode
Dim req As HttpWebRequest = HttpWebRequest.CreateHttp(uri)
Dim resp As HttpWebResponse
Try
resp = DirectCast(req.GetResponse(), HttpWebResponse)
Catch ex As WebException
resp = DirectCast(ex.Response, HttpWebResponse)
End Try
Return resp.StatusCode
End Function

Related

RestSharp call to eBay oauth2 user token

I am trying to get eBay user tokens for my users using the identity api. I finally got it to work in Postman. Converted the call from Postman to a restsharp call from a vb.net test app. The Postman call works, the VB call returns "404 Not Found". Looked at the two calls using Fiddler. The only difference I can see is that the Postman call goes to:
"POST https://api.sandbox.ebay.com/identity/v1/oauth2/token";
and the VB app call goes to
"POST https://api.sandbox.ebay.com/identity/v1/oauth2/token/1"
It would appear that somewhere the VB app is appending "/1" to the api url. Not sure where this is occurring as I can step through the code as it executes and don't see it.
Is there a property in RestSharp that might cause this value to be appended?
EDIT added code. This code is supposed to return a user token and refresh token from eBay. It is taken pretty much from Postman with mods to work with the latest version.
Async Sub RSGetCode(sCode As String)
Dim client As RestClient = New RestClient("https://api.sandbox.ebay.com/identity/v1/oauth2/token")
Dim request As RestRequest = New RestRequest(Method.Post)
sCode = WebUtility.UrlDecode(sCode)
With request
.AddHeader("Content-Type", "application/x-www-form-urlencoded")
.AddHeader("Authorization", "Basic TXVycGh5c0MtNzYxNy00ZGRmLTk5N2ItOD..........................")
.AddParameter("grant_type", "authorization_code")
.AddParameter("code", sCode)
.AddParameter("redirect_uri", "Murphys_Creativ-Mu...........")
.AddParameter("Scope", "https://api.ebay.com/oauth/api_scope/sell.inventory")
End With
Dim responce = Await client.PostAsync(request)
'Dim responce = Await client.ExecuteAsync(request)
Dim sR As String = responce.Content
End Sub```
I got it to work by slightly reformating the code. See below.
Async Sub PostRestCode(sCode As String)
Dim client As RestClient = New RestClient("https://api.sandbox.ebay.com")
Dim request As RestRequest = New RestRequest("identity/v1/oauth2/token", Method.Post)
With request
.AddHeader("Content-Type", "application/x-www-form-urlencoded")
.AddHeader("Authorization", "Basic TXVycGh5c0MtNzYxNy00ZGRmLTk5N2ItODc2OGMzZWZkYT..............................")
.AddParameter("grant_type", "authorization_code")
.AddParameter("code", sCode) '"v^1.1#i^1#I^3#p^3#f^0#r^1#t^Ul41Xzg6NEN.......................................")
.AddParameter("redirect_uri", "Murphys_Creativ-Mu......................")
.AddParameter("Scope", "https://api.ebay.com/oauth/api_scope/sell.inventory")
End With
Dim responce = Await client.PostAsync(request)
'Dim responce = Await client.ExecuteAsync(request)
Dim sR As String = responce.Content
End Sub

How do I check the response code of multiple websites?

i'm a new in VB and i'm trying to make a program that gets and
displays the HTTP response code of a multiple website.
something like:
http response code of target website www.example.com : 200 OK
http response code of target website www.abc2.com : 405 Method Not Allowed
http response code of target website www.testing2.com : 404 Not Found
http response code of target website www.last23.com : 408 RequestTimeout
etc.
I Tried to code it myself but i couldn't , And i also tried to find
online but i didn't found something that works.
i found this code but I think I need a loop to check multiple sites
can you help me with that? how can create loop and check status code
for multiple websites
Public Shared Function GetResponse(uri As String) As HttpStatusCode
Dim req As HttpWebRequest = WebRequest.Create(uri)
Dim resp As HttpWebResponse
Try
resp = DirectCast(req.GetResponse(), HttpWebResponse)
Catch ex As WebException
resp = DirectCast(ex.Response, HttpWebResponse)
End Try
Return resp.StatusCode
End Function
Using the GetResponse function you've already got it's quite simple
Dim sites as new List(of String)
sites.Add("www.example.com")
sites.Add("www.abc2.com")
sites.Add("www.testing2.com")
sites.Add("www.last23.com")
For Each site As String In sites
Dim siteResponse as String = GetResponse(site)
Console.WriteLine("http response code of target website " & site & " " & siteResponse)
Next
That's just off the top of my head so might have a couple gaffs in it

Visual Basic Access Token Youtube API Returning Error 400

So, I'm trying to make a program that will upload videos for me so I don't have to take so much time, and I've come up with the following code:
Imports System
Imports System.Net
Imports System.IO
Module Module1
Sub Main()
Dim bytearray As String = "code=4/5tC9qk5APvWf_05GJRG-Ws5Ph4B1xXMZd0gw4iZEB50&
client_id=349673303318-cp0upvjfcijukhnloppnpl5v57qkrr53.apps.googleusercontent.com&
client_secret=s7gStNsZWua50Hlpot2XfSga&
redirect_uri=https://localhost/oauth2callback&
grant_type=authorization_code"
Dim request As WebRequest = WebRequest.Create("https://accounts.google.com/o/oauth2/token")
request.Credentials = CredentialCache.DefaultCredentials
request.Method = "POST"
request.ContentLength = bytearray.Length
request.ContentType = "application/x-www-form-urlencoded"
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write((Text.Encoding.UTF8.GetBytes(bytearray)), 0, bytearray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
My.Computer.Clipboard.SetText(Convert.ToString(response.GetResponseStream))
response.Close()
End Sub
End Module
This is in Visual Basic.
The problem is that it returns an Error 400 (Bad Request) from the server when I send the request.
Kindly check additional error details then you may refer to YouTube - Errors to help you troubleshoot encountered error.
Additionally, comments in this SO post - Youtube Api : Error 400 Bad Request while uploading videos might also help.

VB.NET | HttpWebRequest, How to see if the host is online?

I am coding a whitelist for my application in VB.NET.
I am using the HttpWebRequest Method and HttpWebResponse.
If the Whitelist Host is down, the whitelist is bypassed and the program is available to anyone which is a vulnerability.
Public Function GetWhitelist(ByVal PageURL As String) As String
Dim S As String = ""
Try
Dim Request As HttpWebRequest = WebRequest.Create("WHITELIST URL HERE")
Dim Response As HttpWebResponse = Request.GetResponse()
Using Reader As StreamReader = New StreamReader(Response.GetResponseStream())
S = Reader.ReadToEnd
End Using
Catch ex As Exception
Debug.WriteLine("Start Program Error. Handle:0")
End Try
Return S
End Function
I want to give the user an error if the website is down, any ideas?
Regards.
What is your error condition? This function alone doesn't prevent anything from happening in the event of an exception. The function still exits with returning a string. So any consuming code would have to look for error conditions and handle them accordingly.
If the request fails, you should meaningfully handle the exception. Two ideas off the top of my head would include:
1) Let the exception bubble up the stack:
Public Function GetWhitelist(ByVal PageURL As String) As String
Dim S As String = ""
Dim Request As HttpWebRequest = WebRequest.Create("WHITELIST URL HERE")
Dim Response As HttpWebResponse = Request.GetResponse()
Using Reader As StreamReader = New StreamReader(Response.GetResponseStream())
S = Reader.ReadToEnd
End Using
Return S
End Function
This would make the attempt to contact the host and, if that attempt failed, throw an exception instead of return a string.
2) Throw a custom exception:
Public Function GetWhitelist(ByVal PageURL As String) As String
Dim S As String = ""
Try
Dim Request As HttpWebRequest = WebRequest.Create("WHITELIST URL HERE")
Dim Response As HttpWebResponse = Request.GetResponse()
Using Reader As StreamReader = New StreamReader(Response.GetResponseStream())
S = Reader.ReadToEnd
End Using
Catch ex As Exception
Debug.WriteLine("Start Program Error. Handle:0")
Throw New SomeCustomException(String.Format("Unable to contact host: {0}", PageURL), ex)
End Try
Return S
End Function
This would provide a more targeted exception instead of whatever comes out of the response reader, would provide useful runtime information about the error for logging and analysis (namely the runtime value of the PageURL), and takes a step toward hiding the implementation details from code outside of this object (since that code doesn't really care about the HttpWebRequest and HttpWebResponse, it just wants to know if the URL is good or not).
Remember that throwing an exception is a perfectly acceptable exit path for a function. It doesn't always have to return a value. An exception is an appropriate way of indicating an error condition. Your current implementation, however, "swallows" the exception and provides no indication to the consuming code that anything went wrong. Instead it returns a "magic value" of String.Empty which consuming code may or may not ignore.
Change your exception handler. The correct way to do this is to just try the request and handle the exception if it fails.

How can I use VB.Net to read the content returned from a URL?

Below is the example code I'm using to get this to work and it does work if I try to read yahoo.com.
Here is the problem. The address I need to read is a java servlet that processes parameters passed in, generates a text document on the server, and then redirects to another URL and returns the address of the text file on the server. I then need to download that text file and process it. I'm having problems connecting to the first URL with the parameters and I think it has to do with the redirect.
I'm using the WebRequest object and I've tried using the HttpWebRequest object. Are there any other objects that support redirects?
TIA
Dim reader As StreamReader
Dim request As WebRequest
Dim response As WebResponse
Dim data As String = ""
Try
request = WebRequest.Create("URL Here")
request.Timeout = 30000
response = request.GetResponse()
reader = New StreamReader(response.GetResponseStream())
data = reader.ReadToEnd()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Return data
Edit
I just tested out HttpWebRequest.Create() and that does handle the 301 and 302 fine with out extra code.
Can you post the error you are seeing
You could cast the WebResponse to a HttpWebResponse:
I need to convert this to VB... but it might help you start:
var response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect)
{
// Follow Redirect, new request based off Redirect
}
// Read Data
I believe you just have to set the AutoRedirect property.
request.AutoRedirect = true;
webRequest = webRequest.Create(URL)
webresponse = webRequest.GetResponse()
inStream = New StreamReader(webresponse.GetResponseStream())
Read URL full source code
winston
I think I found something that will work.
I used a WebBrowser control instead.
Have a button that runs this code...
WebBrowser1.Navigate("URL Here")
And this function to process once the request returns.
Private Sub WebBrowser1_Navigated(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserNavigatedEventArgs) Handles WebBrowser1.Navigated
MsgBox(WebBrowser1.DocumentText)
End Sub