简体   繁体   中英

how to read only headers from response and cancel all the rest using c#?

a server that i want to work with it return 302 Found with some body bytes here is the raw

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

this body bytes i want to cancel it from being downloaded :

<!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>

here is my code manupulating the response using asynchorous request :

  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

the output is null but the response is fully downloaded ! and i want to skip this i want only headers and cancel all the rest of the response stream

so is there any method to read only the headers and cancel all the remaning bytes

To read headers you should check response.Headers collection, without calling GetResponseStream. Have you tried this, is entire body downloaded anyway?

Another thing you may try - is to request data using 'HEAD' request. It is specifically designed to retrieve only headers, always without body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM