json – 跟踪HttpWebRequest和HttpWebResponse的进度

前端之家收集整理的这篇文章主要介绍了json – 跟踪HttpWebRequest和HttpWebResponse的进度前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用发送HTTP请求的Sharefile API并获得各自的答案.它们是通过URL制作的,并始终使用相同的功能.这里是.
Private Function InvokeShareFileOperation(ByVal requestUrl As String) As JObject

    Dim request As HttpWebRequest = WebRequest.Create(requestUrl)
    Dim response As HttpWebResponse = request.GetResponse()

    Dim reader As StreamReader = New StreamReader(response.GetResponseStream())

    Dim json As String = reader.ReadToEnd()
    response.Close()
    Return JObject.Parse(json)

End Function

由于某些操作有点长,我需要以某种方式跟踪他们正在进行的进度并且不知道如何进行.后来我打算使用这个进度并从中创建一个进度条.

(编辑)
顺便说一句,这是占用大部分时间的第二个代码行(下面),即跟踪操作.

Dim response As HttpWebResponse = request.GetResponse()

解决方法

编辑:我认为您无法以任何准确的方式衡量进度,因为大部分操作似乎依赖于处理请求的远程服务器. GetResponse()处理设置DNS,连接,发送和等待远程服务器,这完全不在您手中.只有返回内容长度标头,才能读取响应流.我个人最初会显示20%的进度,GetResponse返回时会显示60%,如果你在下载之前有内容长度,那么最后40%可以逐步显示,或者在读完响应流后一次性完成.

作为Web请求,您可以先查找内容长度,然后使用缓冲区而不是ReadToEnd()读取响应流.这允许您在下载响应时计算进度并触发通知.

Dim request As HttpWebRequest = WebRequest.Create(requestUrl)

Using response As HttpWebResponse = request.GetResponse()
  Dim contentLength As Long = response.ContentLength
  Dim bytesReceived As Long
  Dim bufferLength as Integer = 8192
  Dim buffer(bufferLength) As Char
  Dim sb As New StringBuilder

  Using reader As StreamReader = New StreamReader(response.GetResponseStream())
    Do
      Dim bufferedCount As Integer = reader.Read(buffer,bufferLength)
      sb.Append(buffer,bufferedCount)
      bytesReceived += bufferedCount
      Console.WriteLine(bytesReceived / contentLength * 100 & "%")
    Loop While bytesReceived < contentLength
  End Using

  Return JObject.Parse(sb.ToString)
End Using

显然,您可以使用进度更新功能替换Console.WriteLine或者调用SignalR集线器来更新网页,您可以尝试使用缓冲区大小来查看哪种方法最适合您.

原文链接:https://www.f2er.com/js/150617.html

猜你在找的JavaScript相关文章