0
我想從響應主體只得到11800字節。我正在使用這種方法如何獲得第一個11800字節的響應當文件由php生成不接受(Range-Bytes)?
Public Function getfirstbytes() As String
Try
Dim request As HttpWebRequest = HttpWebRequest.Create("http://example.com/nonresumefile.php")
request.Timeout = 10000
request.KeepAlive = False
Dim BYTES_TO_READ As Integer = 11800
Dim buffer = New Byte(BYTES_TO_READ - 1) {}
Using resp As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Using sm As Stream = resp.GetResponseStream()
Dim totalBytesRead As Integer = 0
Dim bytesRead As Integer
Do
bytesRead = sm.Read(buffer, totalBytesRead, BYTES_TO_READ - totalBytesRead)
totalBytesRead += bytesRead
Loop While totalBytesRead < BYTES_TO_READ
request.Abort() ' this to cancel the remaining bytes (if is a right way)
End Using
End Using
Dim s = Encoding.Default.GetString(buffer)
return s
Catch ex As WebException
Return Nothing
End Try
End Function
這是得到只有第一個11800字節或它得到所有的響應流並選擇第一個18000字節?
你爲什麼叫'request.Abort()'兩次?你正在使用'Using'塊,所以不需要在'resp'或'sm'上調用'Close','Using'塊會爲你做。此外,我不是100%確定,但我不認爲VB.NET支持''+ ='。你有沒有試過運行代碼來看看它做了什麼? – Tim
@Tim感謝您的支持!是的,你是正確的筆記,但是當我檢查與提琴手的響應身體返回所有,不僅首先11800字節 – K3rnel31
不知道你得到的輸出,但一個更簡單的方法來讀取第一個11800字節將是將你的'Read'行改爲'bytesRead = sm.Read(buffer,0,BYTES_TO-READ)' - 它將從流中的位置0開始並讀取到11,800字節。無需跟蹤您讀取多少字節,也無需使用循環。您將首先檢查流的長度;如果它小於11800,你會得到一個ArgumentException錯誤。 – Tim