我如何使用Visual Basic向需要String的服务器发出POST请求?

时间:2014-10-14 09:09:05

标签: java vb.net post request compact-framework

我需要在VB.NET中向我的Tomcat服务器发出一个POST请求,其中一个Java应用程序(由spring和hibernate构建)需要一个JSON字符串。我是VB.NET的新手,我对如何做到这一点没有任何想法。

这是我在VB.NET中的代码(是智能设备的应用程序,因此我使用Compact Framework 3.5)

Private Sub BtnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnLogin.Click
    Dim usuario = TextUsuario.Text
    Dim contraseña = TextContraseña.Text

    Dim userCredentials = New Linq.JObject

    If usuario IsNot "" And contraseña IsNot "" Then
        userCredentials.Add("login", usuario)
        userCredentials.Add("password", contraseña)

        Dim userCredentialsJSON = JsonConvert.SerializeObject(userCredentials)
        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(userCredentialsJSON)

        Try
            Dim url = "http://192.168.2.252:7080/SCTraker_Servidor/api/Session"
            Dim httpWebRequest = WebRequest.Create(url)
            httpWebRequest.Method = "POST"

            httpWebRequest.ContentLength = byteArray.Length
            httpWebRequest.ContentType = "application/x-www-form-urlencoded"

            Dim writer As New StreamWriter(httpWebRequest.GetRequestStream(), System.Text.Encoding.UTF8)
            writer.Write(userCredentialsJSON)
            **writer.Close()**

            Dim dataStream = httpWebRequest.GetResponse.GetResponseStream()
            Dim reader As New StreamReader(dataStream)
            Dim userJSON = reader.ReadLine

            Dim user = Linq.JObject.Parse(userJSON)
            VariablesGlobales.usuario = user

            If user IsNot "" Then
                Me.Hide()
                AJAXJSON.Show()

            Else
                BarraEstado.Text = "No ha rellenado el campo usuario o contraseña"
            End If
        Catch webException As WebException
            Dim status = webException.Status
            BarraEstado.Text = status + ":" + webException.Message

        Catch socketException As Sockets.SocketException
            BarraEstado.Text = socketException.Message

        End Try
    End If
End Sub

这样,服务器在" ** **"的行中返回一个Socket Exception。它说"现有连接被远程主机强行关闭"错误代码:10054

1 个答案:

答案 0 :(得分:0)

我认为这不是你的整个问题,但我无法争辩成功!

  

您当前正在告诉您要发送的服务器   application / x-www-form-urlencoded data。就我而言,你不是   可以告诉,这可能是服务器断开你的原因。

欢迎使用Stack Overflow!