使用WebClient将标准应用程序转换为WP8

时间:2015-05-17 06:01:00

标签: c# windows-phone-8

我有一个应用程序执行很多调用,如

string html = getStringFromWeb(url);
//rest of processes use the html string

我正在尝试将应用程序应用到Windows Phone,并且那里的方法似乎完全不同:

void perform asynch call (...)

void handler
{ string html = e.Result
  //do things with it
}
  1. 只能使用此异步方法从网页获取HTML吗?
  2. 我如何重新设计代码,以便在我调用它时可以使用html?

2 个答案:

答案 0 :(得分:1)

每当您为Web请求工作时,请转到HttpWebRequest。

在Windows Phone 8 xaml / runtime中,您可以使用HttpWebRequest或WebClient来完成。

  

基本上,WebClient是HttpWebRequest的一个包装器。

如果您有一个小请求,那么用户HttpWebRequest。它就像这样

HttpWebRequest request = HttpWebRequest.Create(requestURI) as HttpWebRequest;
WebResponse response = await request.GetResponseAsync();
ObservableCollection<string> statusCollection = new ObservableCollection<string>();
using (var reader = new StreamReader(response.GetResponseStream()))
{
    string responseContent = reader.ReadToEnd();
    // Do anything with you content. Convert it to xml, json or anything.
}

您可以在基本上是异步方法的函数中进行此操作。

来到第1个问题,所有Web请求都将作为异步调用进行,因​​为根据您的网络下载需要一些时间。为了使应用程序不被冻结,将使用异步方法。

答案 1 :(得分:1)

异步方法返回Task。如果您不使用Wait(),代码将继续执行异步方法。如果您不想使用Wait(),则可以使用Callback - 方法作为参数创建异步方法。

使用Wait():

// Asynchronous download method that gets a String
public async Task<string> DownloadString(Uri uri) {
   var task = new TaskCompletionSource<string>();

   try {
      var client = new WebClient();
      client.DownloadStringCompleted += (s, e) => {
         task.SetResult(e.Result);
   };

   client.DownloadStringAsync(uri);
   } catch (Exception ex) {
      task.SetException(ex);
   }

   return await task.Task;
}

private void TestMethod() {
   // Start a new download task asynchronously
   var task = DownloadString(new Uri("http://mywebsite.com"));

   // Wait for the result
   task.Wait();

   // Read the result
   String resultString = task.Result;
}

或使用回调:

private void TestMethodCallback() {

   // Start a new download task asynchronously
   DownloadString(new Uri("http://mywebsite.com"), (resultString) => {
      // This code inside will be run after asynchronous downloading
      MessageBox.Show(resultString);
   });

   // The code will continue to run here
}

// Downlaod example with Callback-method
public async void DownloadString(Uri uri, Action<String> callback) {

   var client = new WebClient();
   client.DownloadStringCompleted += (s, e) => {
      callback(e.Result);
   };

   client.DownloadStringAsync(uri);
}

我当然建议使用回拨方式,因为它在下载String时不会阻止代码运行。

相关问题