Export (0) Print
Expand All

WebRequest.BeginGetResponse Method

When overridden in a descendant class, begins an asynchronous request for an Internet resource.

Namespace:  System.Net
Assembly:  System (in System.dll)

'Declaration
<HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading := True)> _
Public Overridable Function BeginGetResponse ( _
	callback As AsyncCallback, _
	state As Object _
) As IAsyncResult

Parameters

callback
Type: System.AsyncCallback

The AsyncCallback delegate.

state
Type: System.Object

An object containing state information for this asynchronous request.

Return Value

Type: System.IAsyncResult
An IAsyncResult that references the asynchronous request.

ExceptionCondition
NotImplementedException

Any attempt is made to access the method, when the method is not overridden in a descendant class.

The BeginGetResponse method starts an asynchronous request for a response. The callback method that implements the AsyncCallback delegate uses the EndGetResponse method to return the WebResponse from the Internet resource.

NoteNote

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by the descendant class returned by the WebRequest.Create method. For more information about default values and exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.

NoteNote

If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

The following example uses BeginGetResponse to asynchronously request the target resource. When the resource has been obtained, the specified callback method will be executed.

Imports System
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Threading
Imports Microsoft.VisualBasic



Public Class RequestState
  ' This class stores the state of the request 
  Private Shared BUFFER_SIZE As Integer = 1024
  Public requestData As StringBuilder
  Public bufferRead() As Byte 
  Public request As WebRequest
  Public response As WebResponse
  Public responseStream As Stream

  Public Sub New()
    bufferRead = New Byte(BUFFER_SIZE) {}
    requestData = New StringBuilder("")
    request = Nothing
    responseStream = Nothing 
  End Sub ' New 
End Class ' RequestState

Class WebRequest_BeginGetResponse
  Public Shared allDone As New ManualResetEvent(False)
  Private Shared BUFFER_SIZE As Integer = 1024

  Shared Sub Main()
    Try 


      ' Create a new webrequest to the mentioned URL. 
      Dim myWebRequest As WebRequest = WebRequest.Create("http://www.contoso.com")
      'Please, set the proxy to a correct value. 
      Dim proxy As New WebProxy("itgproxy:80")
      proxy.Credentials = New NetworkCredential("srikun", "simrin123")
      myWebRequest.Proxy = proxy
      ' Create a new instance of the RequestState. 
      Dim myRequestState As New RequestState()
      ' The 'WebRequest' object is associated to the 'RequestState' object.
      myRequestState.request = myWebRequest
      ' Start the Asynchronous call for response. 
      Dim asyncResult As IAsyncResult = CType(myWebRequest.BeginGetResponse(AddressOf RespCallback, myRequestState), IAsyncResult)
      allDone.WaitOne()
	  ' Release the WebResponse resource.
	  myRequestState.response.Close()
      Console.Read()
    Catch e As WebException
      Console.WriteLine("WebException raised!")
      Console.WriteLine(ControlChars.Cr + "{0}", e.Message)
      Console.WriteLine(ControlChars.Cr + "{0}", e.Status)
    Catch e As Exception
      Console.WriteLine("Exception raised!")
      Console.WriteLine(("Source : " + e.Source))
      Console.WriteLine(("Message : " + e.Message))
    End Try 
  End Sub ' Main

  Private Shared Sub RespCallback(asynchronousResult As IAsyncResult)
    Try 
      ' Set the State of request to asynchronous. 
      Dim myRequestState As RequestState = CType(asynchronousResult.AsyncState, RequestState)
      Dim myWebRequest1 As WebRequest = myRequestState.request
      ' End the Asynchronous response.
      myRequestState.response = myWebRequest1.EndGetResponse(asynchronousResult)
      ' Read the response into a 'Stream' object. 
      Dim responseStream As Stream = myRequestState.response.GetResponseStream()
      myRequestState.responseStream = responseStream
      ' Begin the reading of the contents of the HTML page and print it to the console. 
      Dim asynchronousResultRead As IAsyncResult = responseStream.BeginRead(myRequestState.bufferRead, 0, BUFFER_SIZE, AddressOf ReadCallBack, myRequestState)
    Catch e As WebException
      Console.WriteLine("WebException raised!")
      Console.WriteLine(ControlChars.Cr + "{0}", e.Message)
      Console.WriteLine(ControlChars.Cr + "{0}", e.Status)
    Catch e As Exception
      Console.WriteLine("Exception raised!")
      Console.WriteLine(("Source : " + e.Source))
      Console.WriteLine(("Message : " + e.Message))
    End Try 
  End Sub ' RespCallback
  Private Shared Sub ReadCallBack(asyncResult As IAsyncResult)
    Try 
      ' Result state is set to AsyncState. 
      Dim myRequestState As RequestState = CType(asyncResult.AsyncState, RequestState)
      Dim responseStream As Stream = myRequestState.responseStream
      Dim read As Integer = responseStream.EndRead(asyncResult)
      ' Read the contents of the HTML page and then print to the console. 
      If read > 0 Then
        myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.bufferRead, 0, read))
        Dim asynchronousResult As IAsyncResult = responseStream.BeginRead(myRequestState.bufferRead, 0, BUFFER_SIZE, AddressOf ReadCallBack, myRequestState)
      Else
        Console.WriteLine(ControlChars.Cr + "The HTML page Contents are:  ")
        If myRequestState.requestData.Length > 1 Then 
          Dim sringContent As String
          sringContent = myRequestState.requestData.ToString()
          Console.WriteLine(sringContent)
        End If
        Console.WriteLine(ControlChars.Cr + "Press 'Enter' key to continue........")
        responseStream.Close()
	       allDone.Set()
      End If 
    Catch e As WebException
      Console.WriteLine("WebException raised!")
      Console.WriteLine(ControlChars.Cr + "{0}", e.Message)
      Console.WriteLine(ControlChars.Cr + "{0}", e.Status)
    Catch e As Exception
      Console.WriteLine("Exception raised!")
      Console.WriteLine("Source :{0} ", e.Source)
      Console.WriteLine("Message :{0} ", e.Message)
    End Try 
  End Sub ' ReadCallBack 

End Class ' WebRequest_BeginGetResponse

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft