2013-10-03 53 views
0

我在這裏有一個工作的HttpWebRequest代碼,但我的問題是它仍然繼續做WebRequest,即使我指定的網站是離線的,這意味着它仍然繼續製作web請求,即使請求從來沒有真正發生過。VB.net檢測到一個失敗的HttpWebRequest

這裏是我的代碼:

  Dim cweb As String = "http://samplewebsiteform.com" 
    Dim POST As String = "name=TestName&age=50" 
      Dim request As HttpWebRequest 

       request = CType(WebRequest.Create(cweb), HttpWebRequest) 
       request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" 
       request.AllowAutoRedirect = False 
       request.ContentType = "application/x-www-form-urlencoded" 
       request.ContentLength = POST.Length 
       request.Method = "POST" 
       request.KeepAlive = False 
       request.Timeout = 500 

       Dim requestStream As Stream = request.GetRequestStream() 
       Dim postBytes As Byte() = Encoding.ASCII.GetBytes(POST) 
       requestStream.Write(postBytes, 0, postBytes.Length) 
       requestStream.Close() 

我如何捕獲此的WebRequest時,它試圖讓一個WebRequest的使用脫機網站,以便將停止發出請求?

回答

1

在請求請求流之前,您沒有收到響應。

這條線:

Dim resphttp As HttpWebResponse = CType(HttpWebResponse, request.GetResponse) 

將讓你獲得網絡響應狀態代碼(404未找到,500錯誤...)

If resphttp.StatusCode <> Net.HttpStatusCode.Accepted Then 
     'There was an error 
End If 

,並請你得到的迴應後, requestStream:

Dim requestStream As Stream = request.GetRequestStream() 
+0

它會依賴於網站的服務器主機多久我會得到迴應? –

+0

這取決於您設置的超時時間;)。你已經使用request.Timeout = 500毫秒。 –

+0

哦,我現在明白了。所以我仍然會像以前一樣獲得相同的速度。謝謝。 –