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

Converting standard application to WP8 with WebClient

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

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?

无论何时处理 Web 请求,请使用 HttpWebRequest。

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

Basically WebClient is a wraper around 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.
}

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

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

异步方法return一个Task。如果不使用 Wait(),代码会继续执行异步方法。如果你不想使用 Wait(),你可以用 Callback-method 作为参数创建一个异步方法。

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.

时阻止来自 运行 的代码