在VB.NET中发布少量数据

时间:2010-02-23 01:53:10

标签: vb.net httpwebrequest webrequest

除了WebRequest类之外,还有另一种轻松在.NET中发出POST请求的方法吗?我需要发布一个非常非常小的数据:

  

密码= theword

...但WebRequest是随机的,我的意思是随机丢弃数据,当发布到我的服务器时。我已经通过使用我服务器中的一大块代码来测试它,该代码将请求转储到控制台,我可以说客户端有时会发送,有时也不会发送POST数据。

我正在使用的使用WebRequest的代码在与IIS通信时在另一个项目中工作。每次通过Firefox向其发送数据时,被通信的服务器(另一个系统中的最小Web服务器)都会正确响应。我在同一个项目中有一个函数可以触发GET请求,这样可行。看起来我的POST函数似乎没有完成事务...过去我曾经注意过要求WebRequest处理小字符串。

这是给我配合的代码。如果有任何.NET专家可以指出我的错误或建议另一个Web客户端,我会非常感激。谢谢!

Private Function PostRequest(ByVal url As String, ByVal data As String) As String
    Return ControlFunctions.PostRequest(url, data, 0)
End Function

Private Function PostRequest(ByVal url As String, ByVal data As String, ByVal times As Integer) As String
    Dim req As HttpWebRequest = WebRequest.Create(url)
    Dim retval As String = ""

    req.Method = "POST"
    req.UserAgent = "TSControl"
    req.ContentType = "application/x-www-form-urlencoded"
    req.ContentLength = data.Length
    req.Headers.Add("Keep-Alive", "300")
    req.KeepAlive = True
    req.Timeout = 5000

    Try
        Dim DataStream As StreamWriter = New StreamWriter(req.GetRequestStream())
        DataStream.AutoFlush = True
        DataStream.Write(data)
        DataStream.Close()

        Dim sr As StreamReader = New StreamReader(req.GetResponse().GetResponseStream())
        retval = sr.ReadToEnd()
        sr.Close()
    Catch x As Exception
        If times < 5 Then
            Threading.Thread.Sleep(1000)
            times = times + 1
            ControlFunctions.PostRequest(url, data, times)
        Else
            ErrorMsg.Show("Could not post to server" + vbCrLf + x.Message + vbCrLf + x.StackTrace)
        End If
    End Try

    Return retval
End Function

---- --- UPDATE

我不得不降低修复它,但幸运的是我在过去的时间里使用过.NET的套接字库:

Private Function PostRequest(ByVal url As String, ByVal data As String) As String
    Dim uri As New Uri(url)
    Dim read(16) As Byte
    Dim FullTime As New StringBuilder
    Dim PostReq As New StringBuilder
    Dim WebConn As New TcpClient

    PostReq.Append("POST ").Append(uri.PathAndQuery).Append(" HTTP/1.1").Append(vbCrLf)
    PostReq.Append("User-Agent: TSControl").Append(vbCrLf)
    PostReq.Append("Content-Type: application/x-www-form-urlencoded").Append(vbCrLf)
    PostReq.Append("Content-Length: ").Append(data.Length.ToString).Append(vbCrLf)
    PostReq.Append("Host: ").Append(uri.Host).Append(vbCrLf).Append(vbCrLf)
    PostReq.Append(data)

    WebConn.Connect(uri.Host, uri.Port)
    Dim WebStream As NetworkStream = WebConn.GetStream()
    Dim WebWrite As New StreamWriter(WebStream)

    WebWrite.Write(PostReq.ToString)
    WebWrite.Flush()

    Dim bytes As Integer = WebStream.Read(read, 0, read.Length)

    While bytes > 0
        FullTime.Append(Encoding.UTF8.GetString(read))
        read.Clear(read, 0, read.Length)
        bytes = WebStream.Read(read, 0, read.Length)
    End While

    ' Closes all the connections
    WebWrite.Close()
    WebStream.Close()
    WebConn.Close()

    Dim temp As String = FullTime.ToString()

    If Not temp.Length <= 0 Then
        Return temp
    Else
        Return "No page"
    End If
End Function

2 个答案:

答案 0 :(得分:2)

如果您收到“分块”回复怎么办?你怎么解码它?

这就是我今天一整天都在苦苦挣扎的事情。如果我正在处理普通的Web服务,我不会挣扎太多,但是我正在创建一个读取eBay API数据的应用程序,eBay有时会发送错误的块大小,这会使解码器破坏响应(即使你的解码器也是如此)通过HTTP 1.1规则解码它。在尝试解码eBay的BAD API这么多个小时后,我终于创建了一个解码VB.net中的分块http响应的函数,并且可以使用众多在线工具中的一个轻松地将其转换为C#。首先,如果响应内容类型被分块,则检查HTTP响应头,如果是,则将响应的主体传递给此函数,该函数通过引用获取变量并对其进行操作:

Public Shared Sub DechunkString(ByRef strString As String)
        Dim intChunkSize As Integer = 0
        Dim strSeperator(0) As String
        strSeperator(0) = vbCrLf

        Dim strChunks As String() = strString.Split(strSeperator, StringSplitOptions.RemoveEmptyEntries)

        strString = ""

        For Each strChunk As String In strChunks
            If strChunk.Length = intChunkSize Then ' for normal behaviour this would be enough
                strString &= strChunk
                intChunkSize = 0
                Continue For
            End If

            ' because of sometimes wrong chunk sizes let's check if the next chunk size is a valid hex, and if not, treat it as part chunk
            If strChunk.Length <= 4 Then ' this is probably a valid hex, but could have invalid characters
                Try
                    intChunkSize = CInt("&H" & strChunk.Trim())

                    If intChunkSize = 0 Then
                        Exit For
                    End If

                    Continue For
                Catch ex As Exception

                End Try
            End If

            ' if got to this point, then add the chunk to output and reset chunk size
            strString &= strChunk
            intChunkSize = 0
        Next
    End Sub

我希望它可以帮助一些人节省大量的时间和精力。

答案 1 :(得分:0)

当您说“.net丢弃数据”时,您的意思是什么?

如果你要做的就是发布一个名值对,你可以按照以下方式进行:

WebClient client = new WebClient();
NameValueCollection nv = new NameValueCollection();
nv.Add("password", "theword");
client.UploadValues(url, "POST", nv);

请注意,您可能必须检查传递给UploadValues的参数的顺序,我不确定此序列是否正确,并且现在太懒了以查找MSDN。