【问题标题】:DownloadStringAsync to get a text string?DownloadStringAsync 获取文本字符串?
【发布时间】:2020-05-07 21:14:53
【问题描述】:

我正在尝试创建一个 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


    【解决方案1】:

    这里有一些问题:

    1. DownloadStringAsync 不返回值(C# 术语中的void 方法)
    2. 您需要为WebClient 变量处理DownloadStringCompleted 事件。您可以在事件处理程序中获取结果。

    您可以将您的代码更改为类似的内容以使上述内容正常工作:

    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
    

    【讨论】:

      【解决方案2】:

      只需使用DownloadStringTaskAsync:

      Using WebClient As WebClient = New WebClient
          Return Await WebClient.DownloadStringTaskAsync(New Uri(myurl))
      End Using
      

      【讨论】:

        猜你喜欢
        • 2011-09-01
        • 2015-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-02
        相关资源
        最近更新 更多