You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用VB.NET调用数独API获取不同难度的数独谜题?

VB.NET实现数独API请求获取不同难度谜题

可以用VB.NET内置的HttpClient轻松实现这个需求,下面是完整的示例代码,支持根据指定难度获取字符串格式的随机数独谜题:

1. 定义JSON响应模型类

首先需要定义一个类来反序列化API返回的JSON数据,适配API返回的结构:

Public Class SudokuResponse
    Public Property puzzle As String
    ' 若API返回其他字段(如难度、解答等),可在此添加对应属性
End Class

2. 核心请求方法

下面的方法接收难度参数(如"easy"、"medium"、"hard",具体有效值以API文档为准),发送请求并返回数独谜题字符串:

Imports System.Net.Http
Imports System.Text.Json

Public Class SudokuApiClient
    Private Shared ReadOnly _httpClient As New HttpClient() With {
        .BaseAddress = New Uri("https://you-do-sudoku-api.vercel.app/")
    }

    Public Async Function GetSudokuPuzzleAsync(difficulty As String) As Task(Of String)
        Try
            ' 构建带难度参数的请求URL
            Dim response = Await _httpClient.GetAsync($"api/sudoku?difficulty={difficulty}")
            response.EnsureSuccessStatusCode() ' 校验请求是否成功

            Dim jsonString = Await response.Content.ReadAsStringAsync()
            Dim sudokuResponse = JsonSerializer.Deserialize(Of SudokuResponse)(jsonString)

            Return sudokuResponse?.puzzle
        Catch ex As HttpRequestException
            Throw New Exception($"请求API失败: {ex.Message}", ex)
        Catch ex As JsonException
            Throw New Exception("解析API响应失败", ex)
        End Try
    End Function
End Class

3. 使用示例

在项目中异步调用方法获取谜题:

Public Async Sub FetchSudokuDemo()
    Dim client As New SudokuApiClient()
    Try
        Dim puzzle = Await client.GetSudokuPuzzleAsync("medium") ' 替换为目标难度
        Console.WriteLine("获取到的数独谜题: " & puzzle)
    Catch ex As Exception
        Console.WriteLine("错误: " & ex.Message)
    End Try
End Sub

额外说明

  • 若API要求用POST请求传递难度参数,可修改请求逻辑:
    Dim requestBody = JsonSerializer.Serialize(New With {.difficulty = difficulty})
    Dim content = New StringContent(requestBody, System.Text.Encoding.UTF8, "application/json")
    Dim response = Await _httpClient.PostAsync("api/sudoku", content)
    
  • .NET Core/.NET 5+默认包含System.Net.Http和System.Text.Json,.NET Framework需手动添加对应NuGet包。

内容的提问来源于stack exchange,提问作者izzi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 03:27:17