Marc Intes
Marc Intes

Reputation: 737

VB.net detecting a failed HttpWebRequest

I have here a working HttpWebRequest code but my problem is it still keeps on doing the WebRequest even if the website I will specify is offline, which means it still keeps on making webrequests even though the request never really happened in the first place.

Here is my code:

            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()

How do i trap this webrequest whenever it tries to make a webrequest with an offline website so that it would stop making the request?

Upvotes: 0

Views: 2093

Answers (1)

Carlos Landeras
Carlos Landeras

Reputation: 11063

You are not getting the Response before requesting the request stream.

This line:

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

Will allow you to get the web response status code (404 not found, 500 error...)

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

And after requesting the response the you get the requestStream:

 Dim requestStream As Stream = request.GetRequestStream()

Upvotes: 1

Related Questions