Home > front end >  Consuming API with authentication from VB.NET
Consuming API with authentication from VB.NET

Time:02-05

Just like it says, I am trying to consume an API that requires I sign in with a user name and password.

The error I am receiving is The remote server returned an error: (403) Forbidden.

Edit: The Authentication type is Basic.

Public Function ForStackOverFlow(requestUri As String)

    Dim response As String

    Dim baseUri = $"http://someapi.example.com/api"
    Dim URI As Uri = New Uri(requestUri)
    Dim credentialCache As New CredentialCache()

    Dim username As String = "username"
    Dim password As String = "password"

    credentialCache.Add(New System.Uri(baseUri), "Basic", New NetworkCredential(username, password))

    Dim request = WebRequest.Create(URI)
    request.ContentType = "application/x-www-form-urlencoded"
    request.Method = "GET"
    request.Credentials = credentialCache

    Using responseStream = request.GetResponse.GetResponseStream
        Using reader As New StreamReader(responseStream)
            response = reader.ReadToEnd()
        End Using
    End Using

    Return response

End Function

Some resources I accessed in trying to solve this problem.

https://docs.microsoft.com/en-us/dotnet/api/system.net.httprequestheader?view=net-6.0

How to consume an asp.net web api in vb.net application

vb.net Task(Of HttpResponseMessage) to HttpResponseMessage

Value of type 'System.Threading.Tasks.Task(Of String)' cannot be converted to 'String'

SSL TLS 1.2 Channel creation VB.net HTTPS WebRequest

Accept self-signed TLS/SSL certificate in VB.NET

Could not establish trust relationship for the SSL/TLS secure channel: The remote certificate is invalid according to the validation procedure

Any and all help is appreciated, Thanks in advanced.

CodePudding user response:

I suggest using HttpClient and also Async/Await:

e.g

    Public Async Function ForStackOverFlow(requestUri As String) As Task(Of String)
        Using client As New HttpClient()
            Dim URI As Uri = New Uri(requestUri)
            Dim auth = Encoding.ASCII.GetBytes("username:password1234")
            client.DefaultRequestHeaders.Authorization = New Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(auth))
            Dim response = Await client.GetAsync(URI)
            Dim content = response.Content
            Return Await content.ReadAsStringAsync()
        End Using
    End Function

Usage:

Dim result = Await ForStackOverFlow("http://SomeURL")
' or 
' Dim result = ForStackOverFlow("http://SomeURL").Result
  •  Tags:  
  • Related