有沒有另一種方式很容易在.NET中發出一個POST請求而不是WebRequest類?我有一個非常,非常小的數據塊我需要張貼:在VB.NET中發佈小數據
密碼= 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
----更新---
我不得不去下修復它,但幸運的是我會使用.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