Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Framework 4 VB.Net Call an API

Tags:

asp.net

vb.net

I am working in an "old" VB.Net application. I wish to make a call to an API, check if I got a 404, parse the JSON result and all the other usual things you can do with an API call.

What is the cleanest way of doing this? I thought I can use the HttpClient class, but I can't apparently! VS 2017 is not giving me the option of adding System.Net.Http as an Import.

CODE

Right now I'm doing this which seems messy.

Public Function GetUserInfo(ByVal authTokenBytes As Byte()) As WebPayWS.GetUserInfoResult
  Dim token As New token
  token.token1 = authTokenBytes
  Dim userInformation As GetUserInfoResult = _myService.GetUserInfo(token)
  If AccountExists(userInformation.accountno) Then
    Dim response As String = GetAccountInfoFromApi(userInformation.accountno)
  End If
  Return userInformation
End Function

Private Function GetAccountInfoFromApi(accountno As String) As String
  Dim accountInformationUrl As String = "URL"
  Dim webClient As WebClient = New WebClient()
  Return webClient.DownloadString(New Uri(accountInformationUrl))
End Function

Am I stuck with WebClient? If yes, how do I check for a 404 using WebClient?

like image 426
J86 Avatar asked Jun 03 '26 20:06

J86


2 Answers

You can wrap it in an exception with the WebClient check this out

Private Function GetAccountInfoFromApi(accountno As String) As String
Dim accountInformationUrl As String = "URL"
Dim webClient As WebClient = New WebClient()
'Return webClient.DownloadString(New Uri(accountInformationUrl))
Dim retString As String

Try 
    retString = webClient.DownloadString(New Uri(accountInformationUrl))

   Catch ex As WebException
    If ex.Status = WebExceptionStatus.ProtocolError AndAlso ex.Response IsNot Nothing Then
        Dim resp = DirectCast(ex.Response, HttpWebResponse)
        If resp.StatusCode = HttpStatusCode.NotFound Then
            ' HTTP 404
            'other steps you want here
        End If
    End If
    'throw any other exception - this should not occur
    Throw
End Try
Return retString

End Function
like image 158
Jimmy Smith Avatar answered Jun 05 '26 17:06

Jimmy Smith


Add a reference first

  • Right click on project
  • Add...
    • Reference...
  • Browse
  • C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Net.Http.dll
  • Ok

enter image description here

Now, you can import

Imports System.Net.Http

You can also use NuGet, see https://stackoverflow.com/a/13668810/832052

like image 43
djv Avatar answered Jun 05 '26 17:06

djv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!