簡體   English   中英

使用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 /運行時中,您可以使用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.
}

您可以使用基本上是異步方法的函數來實現此目的。

關於第一個問題,所有Web請求都將作為異步調用發出,因為根據您的網絡進行下載需要花費時間。 為了不凍結應用程序,將使用異步方法。

異步方法返回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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM