VB 发起 Content-Type 为 application/json 的 POST 请求(带请求体)

发布时间 2023-09-07 22:17:07作者: Higurashi-kagome
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Text

Module Program
    Sub Main(args As String())
        ' 定义 URI 和 JSON 数据
        Dim uri As String = "http://localhost:8556/test"
        Dim jsonData As String = "{ ""key"": ""value"" }"

        ' 发送 POST 请求并获取响应
        Dim responseContent As String = SendJsonPostRequest(uri, jsonData).Result

        ' 处理响应内容
        Console.WriteLine(responseContent)
    End Sub

    Async Function SendJsonPostRequest(uri As String, jsonData As String) As Task(Of String)
        Using client As New HttpClient()
            ' 设置请求头为 "application/json"
            client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))

            ' 构建 HTTP 请求内容
            Dim content As New StringContent(jsonData, Encoding.UTF8, "application/json")

            ' 发送 POST 请求
            Dim response As HttpResponseMessage = Await client.PostAsync(uri, content)

            ' 检查响应是否成功
            If response.IsSuccessStatusCode Then
                ' 读取响应内容
                Dim responseContent As String = Await response.Content.ReadAsStringAsync()
                Return responseContent
            Else
                ' 处理请求失败的情况
                Throw New Exception("请求失败:" & response.ReasonPhrase)
            End If
        End Using
    End Function
End Module

来源:ChatGPT