2010-11-23 68 views
1

我使用了一個tcpclient來建立流媒體API的連接,並且出於某種原因,它不能與301錯誤一起工作(我的證書有問題)。但是,當我使用httpwebrequest到相同的API並使用相同的憑據,並且工作。我試圖找出什麼我做錯了:tcpclient vs httpwebrequest

TcpClient的連接:

  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 

回答

2

HTTP 301是不是一個錯誤,這是一個重定向。 HttpWebRequest可以透明地處理重定向,但如果您自己使用TcpClient自己完成所有HTTP實現,則需要手動解析並遵循重定向。

+0

附加信息:http://en.wikipedia.org/wiki/HTTP_301 – Stefan 2010-11-24 01:19:35