我们有一个基本的打印客户端,它使用Ajax侦听从Web发送的连接。发送了几个可变数据,例如Jquery请求上下文:
$.ajax({
url : 'http://127.0.0.1:13000',
type : 'POST',
data : {
'shipmentNumber': 'SAMPLESN998SSkLAIS',
'labelType': 'labelTypePostageEND',
'pdfLabel': 'pdfLabel__'
}
这被视为
POST / HTTP / 1.1主机:127.0.0.1:13000连接:keep-alive 内容长度:70621接受: / 来源:null User-Agent:Mozilla / 5.0 (Windows NT 10.0; Win64; x64)AppleWebKit / 537.36(KHTML,与Gecko一样) Chrome / 59.0.3071.109 Safari / 537.36内容类型: 应用程序/ x-WWW窗体-urlencoded; charset = UTF-8 Accept-Encoding: gzip,deflate,br Accept-Language:en-GB,en-US; q = 0.8,en; q = 0.6 shipmentNumber = SAMPLESN998SSkLAIS&安培; labelType = labelTypeRoyalMailEND&安培; pdfLabel =
我需要最终得到" labelType"," shipmentNumber"更多(注意,labelType / END是我搜索的字符串,如下所示,不是我想要的数据的一部分),作为要使用的变量,我不确定最好的方法。目前我有(简化):
Dim port As Int32 = 13000
Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1")
server = New TcpListener(localAddr, port)
' Start listening for client requests.
server.Start()
' Buffer for reading data
Dim bytes(10240000) As Byte
Dim data As String = Nothing
' Enter the listening loop.
While True
Dim client As TcpClient = server.AcceptTcpClient()
data = Nothing
' Get a stream object for reading and writing
Dim stream As NetworkStream = client.GetStream()
Dim i As Int32
' Loop to receive all the data sent by the client.
i = stream.Read(bytes, 0, bytes.Length)
data = System.Text.Encoding.ASCII.GetString(bytes, 0, 5000)
' >>>> The bit that matters, split the data based on what we know will be there
Dim searchIndex As Integer = data.IndexOf("labelType")
Dim f As String = data.Substring(searchIndex + 1, data.IndexOf("END", searchIndex + 1) - searchIndex - 1)
MessageBox.Show(data)
' >>> Response and Close connection removed to keep question clean
End While
我可以看到我搜索"标记"的响应。我放在那里的分隔符;感觉它会不可靠,应该有更好的方法。我有seen some questions相关但他们没有directly address this,我不确定这些是否正确。这可能已经是最好的方式,但不要求我不知道。
你会用什么方法来做这件事?
有更好的方法吗?
答案 0 :(得分:1)
使用shipmentNumber=
作为关键字查找参数的开头。然后使用&
分隔符将其拆分。然后循环使用=
分隔符将它们分成参数/值。
data = System.Text.Encoding.ASCII.GetString(bytes, 0, 5000)
Dim dataStart As String = "shipmentNumber="
If data.Contains(dataStart) Then
data = data.Substring(data.IndexOf(dataStart)).Trim
Dim _params() As String = Split(data, "&")
For Each p In _params
Dim _values() As String = Split(p, "=")
If _values.Length > 0 Then
Dim _parameter As String = _values(0)
Dim _value As String = ""
If _values.Length > 1 Then
_value = _values(1)
End If
Debug.Print("parameter = " & _parameter)
Debug.Print("value = " & _value)
End If
Next
End If