使用VB.net发送JSON数据

时间:2014-08-07 19:46:06

标签: json 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

1 个答案:

答案 0 :(得分:0)

不完全确定您要完成的任务,但我相信您正在寻找的是webmethods。

EG: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将参数发布到方法:&#34; application / json;字符集= UTF-8&#34;

<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格式返回数据。