Http Client in Visual Basic .NET
Here’s an idiomatic Visual Basic .NET example demonstrating an HTTP client, similar to the concept shown in the provided Go code:
Imports System
Imports System.Net.Http
Imports System.IO
Module HttpClientExample
Async Function Main() As Task
' Create an instance of HttpClient
Using client As New HttpClient()
Try
' Send an HTTP GET request to a server
Dim response As HttpResponseMessage = Await client.GetAsync("https://example.com")
' Ensure the request was successful
response.EnsureSuccessStatusCode()
' Print the HTTP response status
Console.WriteLine($"Response status: {CInt(response.StatusCode)} {response.StatusCode}")
' Read the response content as a string
Dim content As String = Await response.Content.ReadAsStringAsync()
' Print the first 5 lines of the response body
Using reader As New StringReader(content)
For i As Integer = 0 To 4
Dim line As String = reader.ReadLine()
If line Is Nothing Then Exit For
Console.WriteLine(line)
Next
End Using
Catch ex As HttpRequestException
Console.WriteLine($"Error: {ex.Message}")
End Try
End Using
End Function
End ModuleThis Visual Basic .NET example demonstrates how to use the HttpClient class to make HTTP requests. Here’s a breakdown of the code:
We import necessary namespaces:
Systemfor basic functionality,System.Net.Httpfor HTTP client operations, andSystem.IOfor string reading.The
Mainfunction is marked asAsyncto allow the use of asynchronous operations.We create an instance of
HttpClientinside aUsingblock to ensure proper resource disposal.The
GetAsyncmethod is used to send an HTTP GET request to “https://example.com”. This is equivalent to thehttp.Getfunction in the Go example.We use
EnsureSuccessStatusCodeto throw an exception if the response status code doesn’t indicate success.The response status is printed to the console.
We read the entire response content as a string using
ReadAsStringAsync.A
StringReaderis used to read the first 5 lines of the response content, which are then printed to the console.Exception handling is implemented to catch and display any HTTP request errors.
To run this program:
- Save the code in a file with a
.vbextension (e.g.,HttpClientExample.vb). - Open a command prompt and navigate to the directory containing the file.
- Compile the code using the Visual Basic compiler:
vbc HttpClientExample.vb- Run the compiled executable:
HttpClientExample.exeThis example showcases Visual Basic .NET’s asynchronous programming capabilities and its built-in HTTP client functionality, which are commonly used for making web requests in .NET applications.