VB 發起 Content-Type 爲 application/json 的 POST 請求(帶請求體)

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章