tcpclient vs httpwebrequest

时间:2010-11-23 16:59:04

标签: vb.net visual-studio-2008

我使用tcpclient建立了与流API的连接,由于某种原因,它不能解决301错误(我的凭据有问题)。但是,当我使用httpwebrequest到相同的API并使用相同的凭据,并且工作。我想弄清楚我做错了什么:

TCP客户端连接:

            Try
            Dim bufferread(defaultSize) As Byte
           url = "xxxxxxxxx.com"
            Dim tclient As TcpClient = New TcpClient(url, "80")
            ' use a network stream to download the tcpClient stream
            nstream = tclient.GetStream()
            ' check if we can write to the stream to add the relevant headers and  credentials
            If nstream.CanWrite Then
                Dim headers As String
                headers = "GET " &  addedUrl & " HTTP/1.0" & Chr(13) & "" & Chr(10)
                headers &= "Authorization: Basic " & userNamePassword & Chr(13) & "" & Chr(10)
                headers &= Chr(13) & "" & Chr(10)
                Dim sendBytes As [Byte]() = Encoding.UTF8.GetBytes(headers)
                nstream.Write(sendBytes, 0, sendBytes.Length)
                If nstream.CanRead Then
                    Dim timestamp As DateTime = DateTime.Now
                    Dim data As String
                    numbytesRead = 0
                    ' start reading from the stream
                    Do....

HttpWebRequest的:

    While Not responseData = Nothing
        Try
            ' setup the webrequest and headers to send
            url = "https://xxxxxxxxxxxx.com" & addedUrl 
            If Not parsingTools.refreshDate = Nothing Then
                url = parsingTools.refreshDate
            End If
            Dim poststring As String = ""
            webrequest = TryCast(System.Net.WebRequest.Create(url), HttpWebRequest)
            webrequest.Method = "GET"
            webrequest.UserAgent = "xxxxxxxxxx"
            webrequest.Referer = "xxxxxxxxxxxxx"
            webrequest.Timeout = 20000
            webrequest.KeepAlive = True
            webrequest.Credentials = New System.Net.NetworkCredential ("xxxxxxxxxxxxx", "yyyyyyyyyyyyyy")

            'get the responsestream
            responseStream = webrequest.GetResponse().GetResponseStream()
           'check if stream is readable
            If responseStream.CanRead Then

1 个答案:

答案 0 :(得分:2)

HTTP 301不是错误,它是重定向。 HttpWebRequest可以透明地处理重定向,但是如果您使用TcpClient自己进行所有HTTP实现,那么您需要手动解析并遵循重定向。