Why isn't my super simple program not working???
I did a google search and was shown code that I essentially copied directly. Here is my code:
Code:
Imports System.Net.Http
Module Module1
Private ReadOnly client As New HttpClient()
Sub Main()
Dim response = GetStockPrice("AOA")
End Sub
Async Function GetStockPrice(ticker As String) As Task
Dim baseUrl As String = "https://api.api-ninjas.com/v1/stockprice"
Dim url As String = baseUrl + "?ticker=" + ticker
Dim apiKey As String = "MyAPIkey"
Try
Using request As New HttpRequestMessage(HttpMethod.Get, url)
request.Headers.Add("", apiKey)
Using response As HttpResponseMessage = Await client.SendAsync(request)
response.EnsureSuccessStatusCode()
Dim responseBody As String = Await response.Content.ReadAsStringAsync()
Console.WriteLine("Response Data:")
Console.WriteLine(responseBody)
End Using
End Using
Catch ex As HttpRequestException
Console.WriteLine($"HTTP Error: {ex.Message}")
Catch ex As Exception
Console.WriteLine($"General Error: {ex.Message}")
End Try
End Function
End Module
The code compiled without issue, but when I ran it, nothing appeared on the console. So, I figured I would step through the program, but for some reason, the program exits when it hits the 'using response' line. I double-checked the api-ninja documentation and I do have the header correct.
To double check, I then added an extension to Supermium that allows setting headers. I added the APIkey header, entered the URL in the address bar, and got a proper response. What is wrong with my code?
Re: Why isn't my super simple program not working???
Code:
request.Headers.Add("X-Api-Key", apiKey)
Re: Why isn't my super simple program not working???
Stupid moi - I copied/pasted incorrectly - "X-Api-Key" is actually there.
Re: Why isn't my super simple program not working???
Your main method is calling an asynchronous method without using the await keyword. If you cannot make it async (e.g. it is the starting point of your application), then get the result of the task:
Code:
GetStockPrice("AOA").GetAwaiter().GetResult()
Demo: https://dotnetfiddle.net/VujyVQ
The response I got from your URL using an API key was:
Code:
{"ticker": "AOA", "name": "iShares Core 80/20 Aggressive Allocation ETF", "price": 96.14, "exchange": "AMEX", "updated": 1780949590, "currency": "USD", "volume": 89163.91758}