【问题标题】:how to read only headers from response and cancel all the rest using c#?如何从响应中仅读取标头并使用 c# 取消所有其余部分?
【发布时间】:2014-06-29 20:24:27
【问题描述】:

我想使用它的服务器返回 302 Found 并带有一些正文字节,这是原始的

HTTP/1.1 302 Found
Server: unknown
Date: Sun, 29 Jun 2014 20:12:14 GMT
Content-Type: text/html; charset=utf-8
Connection: close
P3P: CP="CAO PSA OUR"
x-powered-by: 
Set-Cookie: session=604d0bdba04eb54793ec2f3c98b2a37e; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Location: www.mysite.com/login.php?session=604d0bdba04eb54793ec2f3c98b2a37e
Vary: Accept-Encoding
Content-Length: 18163

这个正文字节我想取消它的下载:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
///////body bytes about 18kb///////
</html>

这是我使用异步请求处理响应的代码:

  Dim request As HttpWebRequest = CType(asynchronousResult.AsyncState, HttpWebRequest)


        Dim BYTES_TO_READ As Integer = 0
        Dim buffer = New Byte(BYTES_TO_READ - 1) {}

        Using response As HttpWebResponse = CType(request.EndGetResponse(asynchronousResult), HttpWebResponse)
            Using sm As Stream = response.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()
                response.Close()
                sm.Close()
            End Using
        End Using
        Dim s = Encoding.Default.GetString(buffer)
       Console.WriteLine(s)
    Catch ex As WebException
        Exit Sub
    End Try

输出为空,但响应已完全下载!我想跳过这个我只想要标题并取消所有其余的response stream

那么有什么方法可以只读取标题并取消所有剩余字节

【问题讨论】:

  • 如果您不想要这些数据,请不要阅读它。把所有东西都扔掉。
  • @usr 感谢您的支持!当我处理所有东西时,我可以阅读标题吗?并且正文字节不会被下载?
  • 好吧,您显然在 阅读标题之后处理所有内容。希望这会关闭连接。

标签: c# vb.net stream byte response


【解决方案1】:

要读取标头,您应该检查 response.Headers 集合,而不调用 GetResponseStream。你有没有试过,整个身体都下载了吗?

您可以尝试的另一件事是使用“HEAD”请求来请求数据。它专门设计用于仅检索标题,始终没有正文。

【讨论】:

  • 这个响应是“POST”的结果,我不能使用“HEAD”
  • 我相信这是不可避免的,并且由http决定——如果你开始下载http响应,你还需要下载body。可能自定义 http 实现可以在接收到标头后断开连接,但这将违反协议。你为什么要优化这个?为了节省流量?它只有 18kb
  • 这是多线程大约 5000 个请求,我与 18kb 无关,我只想要标头
猜你喜欢
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
  • 2019-05-27
  • 2014-05-24
  • 2014-03-10
  • 2023-01-14
相关资源
最近更新 更多