使用www.example.com发送JSON数据VB.net

zphenhs4  于 2023-02-06  发布在  .NET
关注(0)|答案(1)|浏览(136)

我正在尝试使用VB .NET将JSON数据发送到Web服务。我正在使用System.Web.Script.Serialization库,但它不工作。当我查看Web服务时,它只显示:{方法=获取MAC地址}

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
njthzxwz

njthzxwz1#

不完全确定你想要完成什么,但我相信你要找的是webmethods。
例如:默认值. 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将参数发布到方法:"应用程序/json;字符集= 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格式的数据。

相关问题