-1

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.

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://learn.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

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Adam Schneider
  • 163
  • 1
  • 12

1 Answers1

1

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
AliReza Sabouri
  • 4,355
  • 2
  • 25
  • 37
  • at Dim response = Await client.GetAsync(New Uri(requestUri)) I get Object reference not set to an instance of an object "This exception was originally thrown at this call stack: [External Code]" I tried to wrap in a try catch but it just enters break mode. – Adam Schneider Feb 04 '22 at 20:10
  • two questions. 1- what dotnet version are you using? 2- make sure to pass a correct URL. – AliReza Sabouri Feb 04 '22 at 20:13
  • 4.7.2. I verified the URL is just like the one that is displayed in swagger when I tested the call I am trying to make. – Adam Schneider Feb 04 '22 at 20:15
  • I've updated the answer. also tested locally now. this version should work as expected. if didn't, paste the error message – AliReza Sabouri Feb 04 '22 at 20:18
  • I tried turning on different exception settings, but all it says is "System.NullReferenceException" Then it says This Exception was originally thrown at this call stack: [External Code]. When I sign in on Swagger it says Authorization Basic, so I would assume we have the auth type correct. – Adam Schneider Feb 04 '22 at 20:26
  • `System.NullReferenceException` means something is null, try to debug line by line and find the null value. – AliReza Sabouri Feb 04 '22 at 20:28
  • I did that, it happens at this line Dim response = Await client.GetAsync(URI) – Adam Schneider Feb 04 '22 at 20:31
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/241741/discussion-between-adam-schneider-and-alireza). – Adam Schneider Feb 04 '22 at 20:32
  • This was the ticket, thank you. – Adam Schneider Feb 04 '22 at 21:30