XAML:
<UserControl x:Class="SilverlightApplication10.webrequestSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="600" Height="400">
<Grid x:Name="LayoutRoot" Background="White">
<TextBox x:Name="tb" FontSize="22" Background="Green"
HorizontalScrollBarVisibility="Visible"
VerticalScrollBarVisibility="Visible"
Foreground="White" Text="Loading..."/>
</Grid>
</UserControl>
VB:
Imports System.IO
Partial Public Class webrequestSample
Inherits UserControl
'定义异步委托方法
Private Delegate Sub DispatcherInvoke(ByVal str As String)
Public Sub New()
InitializeComponent()
'定义URL地址
Dim url As String = "http://www.hzjingwei.gov.cn/hzjingwei2/09jingwei/index.asp"
'创建WebClient对象
Dim request As WebRequest = HttpWebRequest.Create(New Uri(url, UriKind.RelativeOrAbsolute))
'开始获取响应并进行异步回调
request.BeginGetResponse(New AsyncCallback(AddressOf responseReady), request)
End Sub
Private Sub responseReady(ByVal ar As IAsyncResult)
'返回异步回调结果对象
Dim request As WebRequest = TryCast(ar.AsyncState, WebRequest)
'获取结果响应对象
Dim response As WebResponse = request.EndGetResponse(ar)
'定义返回流对象
Using stream As IO.Stream = response.GetResponseStream()
'使用流读取对象
Dim reader As New StreamReader(stream)
'*** 直接读取将发生错误。
'tbk.Text = "reader.ReadToEnd();
'使用Dispatcher异步执行委托方法
tb.Dispatcher.BeginInvoke(DirectCast(AddressOf processResult, DispatcherInvoke), reader.ReadToEnd())
End Using
End Sub
Private Sub processResult(ByVal result As String)
'显示返回字符串
tb.Text = result
End Sub
End Class