簡體   English   中英

使用 VB.net 發送 JSON 數據

[英]Send JSON data using VB.net

我正在嘗試使用 VB.NET 將 JSON 數據發送到 Web 服務。 我正在使用 System.Web.Script.Serialization 庫,但它不起作用。 當我查看 Web 服務時,它只是顯示:{METHOD = getMACAddress}

 Private Function sendWebRequest()
    Dim json As New JavaScriptSerializer
    Dim request As HttpWebRequest = DirectCast(WebRequest.Create("http://192.168.1.1/scripts/service.php"), HttpWebRequest)

    ' Set the Method property of the request to POST.
    request.Method = "POST"
    request.KeepAlive = True
    Dim Data As String =  "{METHOD = getMACAddress}"
    Dim postData As String = json.Serialize(Data)
    MsgBox(Data, 0, "Info")
    Dim byteData As Byte() = Encoding.UTF8.GetBytes(postData)

    ' Set the ContentType property of the WebRequest.
    request.ContentType = "application/x-www-form-urlencoded"
    ' Set the ContentLength property of the WebRequest.
    request.ContentLength = byteData.Length

    ' Get the request stream.
    Dim dataStream As Stream = request.GetRequestStream()
    ' Write the data to the request stream.
    dataStream.Write(byteData, 0, byteData.Length)
    ' Close the Stream object.
    dataStream.Close()

    ' Get the response.
    Dim response As WebResponse = request.GetResponse()
    ' Display the status.
    Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
    ' Get the stream containing content returned by the server.
    dataStream = response.GetResponseStream()
    ' Open the stream using a StreamReader for easy access.
    Dim reader As New StreamReader(dataStream)
    ' Read the content.
    Dim responseFromServer As String = reader.ReadToEnd()
    ' Display the content.
    Console.WriteLine(responseFromServer)
    ' Clean up the streams.
    reader.Close()
    dataStream.Close()
    response.Close()
End Function

不完全確定您要完成什么,但我相信您正在尋找的是網絡方法。

例如:Default.aspx.vb

Inherits System.Web.Services.WebService

<System.Web.Services.WebMethod(BufferResponse:=False)> _
Public Function AddInt(A as Integer, B as Integer) As Integer
    return A + B
End Function

然后從您的客戶端使用確保您使用 contentType: "application/json; charset=utf-8" 將參數發布到方法

<script type="text/javascript">
function GetAddInt() {
    $.ajax({
        type: "POST",
        url: "Default.aspx/AddInt",
        data: '{A: 5, B: 7}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) { alert(response.d); },
        failure: function(response) { alert('Error'); }
    });
}
</script>

雖然這是一個簡單的示例,但您可以通過返回結構化數據或對象來擴展它。 為您處理序列化。

注意:設置內容類型非常重要,否則 .NET 將以 XML 格式返回數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM