如何在VB.NET中实现调用CoinGecko API的指定Curl请求?
在VB.NET中调用CoinGecko API的实现方案
原Curl请求对应需求
你需要实现的Curl请求是获取比特币的USD价格,参数已指定不需要额外扩展数据,请求格式为JSON:
curl -X 'GET' \ 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_market_cap=false&include_24hr_vol=false&include_24hr_change=false&include_last_updated_at=false&precision=full' \ -H 'accept: application/json'
以下是两种可行的VB.NET实现方式:
方法1:使用HttpClient(推荐,适用于.NET Core/.NET 5+及新版.NET Framework)
HttpClient是.NET官方推荐的现代HTTP客户端,支持异步操作,性能更优且资源占用合理。
完整示例代码
Imports System.Net.Http Imports System.Text.Json Module CoinGeckoApiExample ' 全局单例HttpClient,避免重复创建导致端口耗尽 Private ReadOnly _httpClient As New HttpClient() Async Function GetBitcoinPriceAsync() As Task(Of Decimal?) Try ' 构造请求URL Dim requestUrl As String = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_market_cap=false&include_24hr_vol=false&include_24hr_change=false&include_last_updated_at=false&precision=full" ' 设置请求头 _httpClient.DefaultRequestHeaders.Accept.Clear() _httpClient.DefaultRequestHeaders.Accept.Add(New System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")) ' 发送GET请求并获取响应 Dim response As HttpResponseMessage = Await _httpClient.GetAsync(requestUrl) response.EnsureSuccessStatusCode() ' 抛出HTTP错误状态码异常 ' 读取并解析JSON响应 Dim jsonResponse As String = Await response.Content.ReadAsStringAsync() Dim priceData As Dictionary(Of String, Dictionary(Of String, Decimal)) = JsonSerializer.Deserialize(Of Dictionary(Of String, Dictionary(Of String, Decimal)))(jsonResponse) ' 提取比特币USD价格 Return priceData("bitcoin")("usd") Catch ex As HttpRequestException Console.WriteLine($"请求出错:{ex.Message}") Return Nothing Catch ex As KeyNotFoundException Console.WriteLine("API返回数据格式异常") Return Nothing End Try End Function ' 调用示例(需在异步上下文执行) Async Sub Main() Dim price As Decimal? = Await GetBitcoinPriceAsync() If price.HasValue Then Console.WriteLine($"当前比特币价格:${price.Value:N2}") Else Console.WriteLine("无法获取比特币价格") End If End Sub End Module
补充说明
HttpClient必须全局单例使用,禁止每次请求时创建新实例,否则会导致系统端口耗尽。- 若使用.NET Framework,需确保项目引用了
System.Net.Http程序集。 - 若偏好使用Newtonsoft.Json(Json.NET)解析JSON,可替换反序列化代码:
Imports Newtonsoft.Json ' ... Dim priceData As Dictionary(Of String, Dictionary(Of String, Decimal)) = JsonConvert.DeserializeObject(Of Dictionary(Of String, Dictionary(Of String, Decimal)))(jsonResponse)
方法2:使用WebClient(适用于旧版.NET Framework)
WebClient是较旧的HTTP客户端,API简单但功能有限,不推荐在新项目中使用。
示例代码
Imports System.Net Imports Newtonsoft.Json ' 需要引用Newtonsoft.Json NuGet包 Module CoinGeckoWebClientExample Function GetBitcoinPrice() As Decimal? Try Dim requestUrl As String = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_market_cap=false&include_24hr_vol=false&include_24hr_change=false&include_last_updated_at=false&precision=full" Using webClient As New WebClient() webClient.Headers.Add(HttpRequestHeader.Accept, "application/json") Dim jsonResponse As String = webClient.DownloadString(requestUrl) Dim priceData As Dictionary(Of String, Dictionary(Of String, Decimal)) = JsonConvert.DeserializeObject(Of Dictionary(Of String, Dictionary(Of String, Decimal)))(jsonResponse) Return priceData("bitcoin")("usd") End Using Catch ex As WebException Console.WriteLine($"请求出错:{ex.Message}") Return Nothing Catch ex As KeyNotFoundException Console.WriteLine("API返回数据格式异常") Return Nothing End Try End Function Sub Main() Dim price As Decimal? = GetBitcoinPrice() If price.HasValue Then Console.WriteLine($"当前比特币价格:${price.Value:N2}") Else Console.WriteLine("无法获取比特币价格") End If End Sub End Module
内容的提问来源于stack exchange,提问作者John Paul Attard
相关产品推荐
相关产品推荐

