DownloadStringAsync获取文本字符串?

问题描述 投票:0回答:2

我正试图创建一个Windows Phone 7.1应用程序,基本上是一个货币转换器。我正在使用 DownloadStringAsync 方法从一个特定的网站上获取一个包含汇率的短字符串。我在Visual Studio 2010中进行了测试。DownloadString 工作就好了。但是手机应用就不行了。我需要在这里做什么?我真的搞不清楚。

Partial Public Class MainPage
Inherits PhoneApplicationPage
Dim webClient As New System.Net.WebClient
Dim a As String
Dim b As String
Dim result As String = Nothing
' Constructor
Public Sub New()
    InitializeComponent()
End Sub

Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
    a = "USD"
    b = "GBP"
    webClient = New WebClient
    Dim result As String = webClient.DownloadStringAsync(New Uri("http://rate-exchange.appspot.com/currency?from=" + a + "&to=" + b) as String)
    TextBox1.Text = result
End Sub

结束类

vb.net visual-studio-2010 windows-phone windows-phone-7.1 downloadstring
2个回答
2
投票

这里有几个问题。

  1. DownloadStringAsync 没有返回一个值(void 方法)
  2. 你需要处理 DownloadStringCompleted 活动 WebClient 变量。你可以在事件处理程序中得到结果。

你可以把你的代码改成类似这样的方式来让上面的代码工作。

Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
    a = "USD"
    b = "GBP"
    webClient = New WebClient
    'Add the event handler here
    AddHandler webClient.DownloadStringCompleted, AddressOf webClient_DownloadStringCompleted            
    Dim url As String = "http://rate-exchange.appspot.com/currency?from=" & a & "&to=" & b            
    webClient.DownloadStringAsync(New Uri(url))
End Sub

Private Sub webClient_DownloadStringCompleted(ByVal sender as Object,ByVal e as DownloadStringCompletedEventArgs)
    TextBox1.Text = e.result
End Sub

0
投票

只要使用 DownloadStringTaskAsync:

Using WebClient As WebClient = New WebClient
    Return Await WebClient.DownloadStringTaskAsync(New Uri(myurl))
End Using
© www.soinside.com 2019 - 2024. All rights reserved.