'VB.Net - Function to get text from a web page using httpclient
I am able to write a "Task" function to get the text from a single web page. But I want to make a function that takes the url as an input and returns the text from the web page (so that I can keep the GET part separate from the rest of my code.
Here is the code that I have working:
Private components As System.ComponentModel.IContainer
ReadOnly client As HttpClient = New HttpClient()
Private Async Function MyWebResponse() As Task
Dim myUrl As String
myUrl = "https://statsapi.mlb.com/api/v1.1/game/632201/feed/live/diffPatch"
' Call asynchronous network methods in a try/catch block to handle exceptions.
Try
Dim response As HttpResponseMessage = Await client.GetAsync(myUrl)
response.EnsureSuccessStatusCode()
Dim responseBody As String = Await response.Content.ReadAsStringAsync()
Catch e As HttpRequestException
Console.WriteLine(Environment.NewLine & "Exception Caught!")
Console.WriteLine("Message :{0} ", e.Message)
MsgBox(e.Message)
End Try
End Function
I want to turn this into a function that returns the responseBody as a string. Something like:
Dim myUrl As String
myUrl = "https://statsapi.mlb.com/api/v1.1/game/632201/feed/live/diffPatch"
myString = MyWebResponse(myUrl)
I haven't been able to figure out a way to convert the function to the kind that returns something. If I make it into Task(Of String) it fails because you can't put a Task(Of String) into a String variable. But if I try to make it a string instead of a Task then I can't have the async and Await stuff and then the Httpclient commands don't work because they require async and Await. At this point it looks like all of my code has to go into a single block of code where I loop through urls and do stuff with the responses. But if I can't make the code modular, it will be extremely difficult to work with and maintain.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
