我想从站点获取特殊数据,但我不知道如何获取。
我需要一个 vb.net 源代码,它有助于每 5 秒从 Web 获取这些数据并将它们拆分成一个表单。
我怎样才能做到这一点?
看起来网页上的数据是压缩的,所以如果你一直试图通过WebClient.DownloadString
或WebClient.DownloadData
System.Text.Encoding.UTF8.GetString
来获取数据,那么你将不会得到一个可读的字符串。字符串可能如下所示
是?J?7?s?H4??N???{?vS(????7?不±?O?f??E???-?O??q(?m,:K?:?{Ij.??J?乌姆??-K?ni=KT???c?'?g??-??]??一个???答?>???o???????是??>??????5GA??Z[?v??s?F????i?eU?/?+,??!?f?9?t?2;bG???(??Y!??牛??通用 汽车??W???????Z???8????=?y?吴语??9??7;z?^??????T??Y?8]比??|N? ...
您可以看到响应的编码是用以下内容压缩的
client.ResponseHeaders(HttpResponseHeader.ContentEncoding)
' equals gzip
所以做简单
client.DownloadString(address)
将导致压缩字符串。要考虑压缩,请使用System.IO.GZipStream
解压缩。
此代码已完成。您要做的就是创建一个新表单,添加新标签,然后粘贴此
Public Class Form1
Private ReadOnly interval As Integer = 5000
Private ReadOnly t As New System.Threading.Timer(AddressOf updateLabel, Nothing, -1, -1)
Private ReadOnly address As String = "http://www.tsetmc.com/tsev2/data/instinfodata.aspx?i=35425587644337450&c=27+"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
t.Change(0, -1)
End Sub
Private Sub updateLabel(state As Object)
Dim text As String
Try
text = getString(address)
t.Change(interval, -1)
Catch
text = "error"
End Try
Label1.Invoke(Sub() Label1.Text = text)
End Sub
Private Shared Function getString(address As String) As String
Dim text As String
Using client As New Net.WebClient()
Using stream = client.OpenRead(address)
If client.ResponseHeaders(Net.HttpResponseHeader.ContentEncoding) = "gzip" Then
Using responseStream = New IO.Compression.GZipStream(stream, IO.Compression.CompressionMode.Decompress)
Using reader = New IO.StreamReader(responseStream)
text = reader.ReadToEnd()
End Using
End Using
Else
Using reader = New IO.StreamReader(stream)
text = reader.ReadToEnd()
End Using
End If
End Using
End Using
Return text
End Function
End Class
上面的代码允许压缩或非压缩响应。如果你知道它总是被压缩的,你可以使用它
Private Shared Function getString(address As String) As String
Dim text As String
Using client As New Net.WebClient()
Using stream = client.OpenRead(address)
Using responseStream = New IO.Compression.GZipStream(stream, IO.Compression.CompressionMode.Decompress)
Using reader = New IO.StreamReader(responseStream)
text = reader.ReadToEnd()
End Using
End Using
End Using
End Using
Return text
End Function
您现在应该得到一个可读的字符串
12:29:37,A ,5254,5218,5203,5223,5277,5190,1727,16938744,88393224291,1,20191125,122937;98/9/4 14:31:01,F,308477.15,2703.04 0.88%,11256322598042802,2998595530,15357456521865,388202,F,986363991,12363278355103,190712,F,606761,179231120000,6176,;4@63890@5230@5254@100000@2,4@120000@5228@5255@6500@1,2@40000@5222@5259@221500@6,;65589,406538,760335;10352685,6586059,0,14312016,2626728,573,19,0,456,12;;;0;