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 Module
This 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:
System
for basic functionality,System.Net.Http
for HTTP client operations, andSystem.IO
for string reading.The
Main
function is marked asAsync
to allow the use of asynchronous operations.We create an instance of
HttpClient
inside aUsing
block to ensure proper resource disposal.The
GetAsync
method is used to send an HTTP GET request to “https://example.com”. This is equivalent to thehttp.Get
function in the Go example.We use
EnsureSuccessStatusCode
to 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
StringReader
is 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
.vb
extension (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.exe
This 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.